【问题标题】:How to display a badge when a chat thread has unread messages React JS, Firestore当聊天线程有未读消息时如何显示徽章React JS,Firestore
【发布时间】:2021-07-09 04:01:54
【问题描述】:

我正在用 React 和 firebase firestore 开发一个聊天应用程序。每次将新消息添加到数据库时,我都想显示未读消息标记。目前,我正在使用 useEffect 挂钩来检查是否读取了最后一条消息,并且仅在页面第一次呈现时才有效 - 未读消息标记仅在我重新加载页面后出现。我想我想不通的是每次状态变化时如何重新渲染。请查看我的代码并告诉我我缺少什么。我希望我的问题很清楚。提前致谢。

const [chatMessages, setChatMessages] = useState([])
const [isRead, setIsRead] = useState(false)

const readsRef = db.collection('rooms').doc(id).collection('messages')

useEffect(() => {

    const unsubscribe = readsRef.orderBy('timestamp', 'desc')

        .limit(1).onSnapshot((snapshot) => {
            snapshot.docs.map((snap) => {
                setChatMessages(snap.data().message)

                 readsRef.doc(snap.id).collection('read').doc(userID.uid).onSnapshot((snapshot1 => {
                    if (snapshot1.get('readReceipt') === userID.uid) {
                        setIsRead(true)
   
                    }
            
                }))

            })

    })
    return unsubscribe;
    
}, [isRead])


 return (

 <SidebarOptionChannel>

                   
    <span># </span>{title} - {chatMessages}<span>{isRead ? null : <UnreadBadge> 
    <span>1</span></UnreadBadge>  }</span>

  </SidebarOptionChannel>
 )

【问题讨论】:

  • 什么是 readReports?
  • 看起来代码不完整,isRead 被添加为 useEffects 的依赖项,但我没有看到任何状态变量 isRead。用适当的细节更新问题,代码沙箱链接会更好
  • 对不起!我已经对其进行了编辑以包含变量。请再次检查

标签: reactjs firebase google-cloud-firestore use-effect use-state


【解决方案1】:

解决您的问题的另一种方法可能是通过侦听 Firebase 数据库中的更改来更新您的聊天应用程序。这可以通过使用 firebase.database.Reference 的方法来完成:

on() 或 once()

以下是 Firebase 的documentation 提供的示例:

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', (snapshot) => {
  const data = snapshot.val();
  updateStarCount(postElement, data);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    相关资源
    最近更新 更多