向 firestore 发送有天赋的聊天消息时,有没有办法修复 React Native 的 "Encountered two children with the same key" 错误?

Is there a way to fix the "Encountered two children with the same key" error on react native when sending gifted chat messages to firestore?

我已经使用 gifted chat ui 和 firestore 数据库设置了一个 React Native 群聊应用程序,但是我在 运行 应用程序后一直收到此错误。

Warning: Encountered two children with the same key

错误似乎来自 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。

您的数据似乎缺少唯一的 _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 ??