1

我已经使用带有 firestore 数据库的天才聊天 ui 设置了一个反应本机群聊应用程序,但是一旦我运行该应用程序,我就会不断收到此错误。

警告:遇到两个孩子使用相同的钥匙

在此处输入图像描述 错误似乎来自 getMessages 方法

  parseMsgsFromFirestore = snapshot => {
    const { id: _id } = snapshot;
    const { text, user } = snapshot.doc.data();
    const stampInSeconds = snapshot.doc.data().timestamp.seconds;
    const timestamp = new Date(stampInSeconds * 1000);
    const message = {
      _id,
      timestamp,
      text,
      user
    };
    return message;
  };

  getMessages = callback => {
    firebase
      .firestore()
      .collection('messages')
      .orderBy('timestamp')
      .onSnapshot(snapshot => {
        const changes = snapshot.docChanges();
        // TODO: Warning: Encountered two children with the same key {Error occurs in about 5 minutes and then persists}
        changes.map(change => callback(this.parseMsgsFromFirestore(change)));
      });
  };

  sendMessages = messages => {
    // sending only specific properties to firestore
    for (let i = 0; i < messages.length; i++) {
      const { text, user } = messages[i];
      const message = {
        text,
        user,
        timestamp: firebase.firestore.Timestamp.fromDate(new Date())
      };
      this.concat(message);
    }
  };

  concat = message => {
    firebase
      .firestore()
      .collection('messages')
      .add(message);
  };

在我的 Chat.js 文件中,我在 componentDidMount 方法上调用该方法。

import React, { Component } from 'react';
import { GiftedChat } from 'react-native-gifted-chat';
import fireStoreDB from '../database/FirestoreDB';

export default class Chat extends Component {
  static navigationOptions = ({ navigation }) => ({
    title: navigation.getParam('name')
  });

  constructor(props) {
    super(props);
    this.state = {
      messages: []
    };
  }

  componentDidMount() {
    fireStoreDB.getMessages(message =>
      this.setState(previousState => ({
        messages: GiftedChat.append(previousState.messages, message)
      }))
    );
  }

  componentWillUnmount() {
    fireStoreDB.signUserOut();
    fireStoreDB.snapOff();
  }

  get user() {
    return {
      // gifted chat user props
      name: this.props.navigation.getParam('name'),
      _id: fireStoreDB.uid
    };
  }

  render() {
    return (
      <GiftedChat
        messages={this.state.messages}
        onSend={fireStoreDB.sendMessages}
        user={this.user}
      />
    );
  }
}

我所有的消息密钥在数据库中都是唯一的,除了它们都来自同一个用户 ID。 我所有的密钥在数据库中都是唯一的。

4

1 回答 1

2

您的数据似乎缺少唯一_id字段。从这行代码可以看出https://github.com/FaridSafi/react-native-gifted-chat/blob/master/src/MessageContainer.tsx#L281

key: item._id,

这就是key它抱怨的地方。确保您的消息有一个_id字段并确保它们是唯一的。

现在你有User._id,但顶级消息也应该有它自己的_id.

const { text, user } = messages[i]; // Does this have _id ??
于 2019-11-01T21:59:42.677 回答