我即将在聊天应用程序中取得成功,这涉及到从数据库中监视用户状态。我正在使用Firebase云Firestore。我正在尝试使用“ onSnapshot”在firebase文档中更改用户的联机状态和打字状态以进行更新。它工作正常,但每次进行更改时,进行更改的用户就会在用户显示部分中增加。这就更像是每次更改时都会添加到用户状态的循环...请我需要知道我是否在某个地方犯了错误...在此方面我需要帮助。
这是我的代码:
getUsers = () => {firebase.firestore().collection('users').onSnapshot(snapshot => {
snapshot.docChanges().forEach((change, index) => {
this.docChanged.push({
key: index,
documentKey: change.doc.id,
id: change.doc.data().id,
name: change.doc.data().name,
messages: change.doc.data().messages,
URL: change.doc.data().URL,
description: change.doc.data().description,
online: change.doc.data().online,
typing: change.doc.data().typing
})
console.log(change.doc.data())
})
this.setState({
loading: false
})
this.renderUserList()
}
)
}
我将用户吸引到这里...使用“ onSnapshot”,因为我需要它随着状态变化而更新...
这是我的renderUserList代码:
renderUserList = () => {
if(this.docChanged.length > 0 ) {
let viewUserList = [];
let classname = ''
this.docChanged.map((item, index) => {
if(item.id !== this.currentUserId){
classname = this.userAndNotificationClass(item.id);
viewUserList.push(
<>
<Button
style={{padding: '20px'}}
id={item.key}
key={index}
className={classname}
onClick={() => {
this.notificationErase(item.id)
this.setState({currentPeerUser: item})
// document.getElementById(item.key).style.backgroundColor = '#392493'
// document.getElementById(item.key).style.color = 'white'
}}
>
<div>
<Avatar style={{width: '50px', height: '50px'}} src={item.URL} className='viewAvatarItem' alt='' />
{localStorage.getItem(SigninString.online) && item.online ? (
<Avatar src='online.png' alt='' style={{position: 'absolute', width: '20px', height: '20px',marginLeft: '55px', marginTop: '-18px'}} />
) : <Avatar src='offline.png' alt='' style={{position: 'absolute', width: '16px', height: '16px',marginLeft: '55px', marginTop: '-18px'}} />}
</div>
<div className='viewWrapContentItem' >
<span className='textItem' >
{item.name}
</span>
<span >
{item.typing ? (
<p style={{marginLeft: '0px',
position: 'absolute', textTransform: 'lowercase', marginTop: '-5px'}} >typing...</p>
) : null}
</span>
</div>
{classname === 'viewWrapItemNotification' ?
<div className='notificationpragraph' >
<p id={item.key} key={index} className='newmessages' >New Messages</p>
</div> : null}
</Button>
<Divider />
</>
)
}
})
this.setState({
displayedContact: viewUserList
})
}else{
console.log('No user is available.')
}
}
componentDidMount = () => {
this.getUsers()
}
如果您不明白我的意思...请在此处https://i.stack.imgur.com/NCaLb.png查看此文件
在图像文件中,您将看到“ Kelly Owoju”在用户列表中出现了两次...我不知道该怎么做才能阻止这种情况的发生...它的发生取决于状态的变化数据库...
如果Typing是“ true”,则它会更改...如果“ online”是true或false,它也会更改...
我希望任何人都能理解...我需要帮助。