【发布时间】:2021-09-23 22:50:29
【问题描述】:
我正在使用 Firestore 后端在 React Native 上构建一个聊天应用程序。
我的结构是这样的:
Channels
-Channel
{
user1,
user2,
messages:[] (This is a subcollection not an array inside the document)
}
我想检查是否有频道包含所选用户。
检查器功能:
const [chatRef, setChatRef] = useState()
let channelRef = db.collection("Channels")
channelRef.get().then((snapshot) => {
snapshot.forEach((doc) => {
let room = doc.data()
if (
(room.user1.id === user.id || room.user2.id === user.id) &&
(room.user1.id === personToChat.id || room.user2.id === personToChat.id)
) {
setChatRef(channelRef.doc(room.id).collection("Messages"))
} else {
channelRef.doc(user.id).set({
user1: user,
user2: personToChat,
})
setChatRef(channelRef.doc(user.id).collection("Messages"))
}
})
})
使用效果:
useEffect(() => {
const unsubscribe = chatRef.onSnapshot((querySnapshot) => {
const messagesFirestore = querySnapshot
.docChanges()
.filter(({ type }) => type === "added")
.map(({ doc }) => {
const message = doc.data()
return { ...message, createdAt: message.createdAt.toDate() }
})
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
appendMessages(messagesFirestore)
})
return () => unsubscribe()
}, [])
我尝试了什么?
- 我尝试使用变量而不是状态。没用。
- 我尝试使用函数获取 chatRef 变量。没用。
- 我使用 chatRef 作为依赖项。没用。
- 我在 useEffect 中调用了检查函数。没用。
所有这些都会导致相同的错误,即,
TypeError: undefined is not an object (evaluating 'chatRef.onSnapshot')
【问题讨论】:
-
您的
chatRef状态未定义,因此OFCchatRef.onSnapshot在效果运行时会抛出错误。您希望channelRef.get()何时运行并最终设置chatRef状态?另外,作为 React 中的命名约定,如果变量实际上不是 React ref,请不要在变量中添加“-Ref”后缀,否则其他人可能会发现很难准备好您的代码。
标签: javascript reactjs firebase react-native google-cloud-firestore