我已经使用有天赋的聊天ui和firestore数据库设置了一个react native群组聊天应用程序,但是运行该应用程序后,我一直收到此错误。
警告:使用相同的键遇到了两个孩子
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}
/>
);
}
}
答案 0 :(得分: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 ??
答案 1 :(得分:0)
您可以在utils.js中使用此方法来生成一个id,您需要_id消息字段:
application/json; charset=utf-8