【发布时间】:2021-01-20 05:05:43
【问题描述】:
我正在尝试在我的 react 本机应用程序中创建聊天功能。我正在使用 react-native-gifted-chat 并将消息保存在 Firestore 中。这是正在发生的行为:
当我发送消息时,所有消息都会重新呈现,其中一些是重复的,如您所见,到目前为止我只发送了 3 条消息,但是所有这些重复让我想知道为什么整个事情都在重新呈现以及为什么在重新渲染时会出现重复。
代码:
class Chat extends React.Component {
constructor(props) {
super(props)
this.state = {
messages: [],
currentUser: null,
isLoading: true,
messageID: ""
}
}
//---------------------------------------------------------------
async componentDidMount (){
// get user info from firestore
let userUID = Firebase.auth().currentUser.uid
await Firebase.firestore().collection("users").doc(userUID).get()
.then(doc => {
data = doc.data()
this.setState({
currentUser: {
name: data.username,
avatar: data.profilePic,
_id: doc.id,
},
})
})
const messages = []
await Firebase.firestore().collection("chat")
.orderBy("createdAt", "desc")
.limit(50)
.onSnapshot(querySnapshot => {
querySnapshot.forEach((res) => {
const {
user,
text,
createdAt,
} = res.data();
messages.push({
key: res._id,
user,
text,
createdAt,
});
})
this.setState({
messages,
isLoading: false,
});
})
}
//Load 50 more messages when the user scrolls
//
//Add a message to firestore
onSend = async(message) => {
await Firebase.firestore().collection("chat")
.add({
user: {
_id: this.state.currentUser._id,
name: this.state.currentUser.name,
avatar: this.state.currentUser.avatar,
},
})
.then(ref => this.setState({messageID: ref.id}))
await Firebase.firestore().collection("chat")
.doc(this.state.messageID)
.set({
_id: this.state.messageID,
text: message[0].text,
createdAt: message[0].createdAt
}, { merge: true })
}
render() {
if(this.state.isLoading){
return(
<View style = {{backgroundColor: '#000000', flex: 1}}>
<ActivityIndicator size="large" color="#9E9E9E"/>
</View>
)
}
return (
<View style={{backgroundColor: '#000000', flex: 1}}>
<GiftedChat
showUserAvatar={true}
renderUsernameOnMessage={true}
messages={this.state.messages}
onSend={message => this.onSend(message)}
scrollToBottom
/>
</View>
)
}
}
一些注意事项:
- 每次组件挂载时,消息数组都会将消息推送到状态数组。
- 组件在我发送消息时挂载,从而重新呈现消息数组
- 每个消息 ID 都是唯一的,由 firebase 使用“添加”生成
请告诉我如何解决此问题!谢谢
【问题讨论】:
-
我已经修复了“无效日期”的问题,但是看到重复和整个重新渲染的问题仍然是一个问题。
-
更多进展:删除对 firestore 的调用以从组件中加载更多消息 Mount 没有解决问题,所以在我看来,问题在于如何将消息添加到消息数组中状态 - 现在是晚上 10 点,如果我能醒来找到解决方案,我将永远感激不尽
-
您是如何解决无效日期问题的?
-
@R.CanserYanbakan createdAt: Moment(message[0].createdAt).format('LLL')
标签: react-native google-cloud-firestore react-native-gifted-chat