我在聊天應用程式中遇到問題。
我在將訊息檔案發布到訊息 col 時作業,但隨后我嘗試回傳 getDocs 并渲染它們,我得到一個空陣列。
我瀏覽了 FB 檔案,我沒有發現任何錯誤。我還閱讀了一篇文章,建議我將 react-firebase 庫與 useCollectionData 一起使用,結果相同。
const [messages, loading] = useCollectionData(
firestore.collection('messages').orderBy('createdAt')
)
我嘗試了不同的方法,但似乎沒有任何效果。
import React, { useState, useEffect } from 'react'
import { auth, db, app } from '../../firebase.config'
import { useAuthState } from 'react-firebase-hooks/auth'
import { useCollectionData } from 'react-firebase-hooks/firestore'
import { docs, onSnapshot, query, where, addDoc, collection, serverTimestamp, orderBy, getDocs } from 'firebase/firestore'
import Message from '../Message/Message'
import Spinner from '../Spinner/Spinner'
import './chat.css'
const Chat = () => {
const [user, loading, error] = useAuthState(auth)
const [value, setValue] = useState('')
const [msgs, setMsgs] = useState([])
console.log('msgs>>>>', msgs)
useEffect(() => {
const fetchMsg = async () => {
const messagesRef = collection(db, 'messages')
const q = query(
messagesRef,
orderBy('timestamp', 'desc')
)
const querySnap = await getDocs(q)
let listings = []
querySnap.forEach((doc) => {
return listings.push({
id: doc.id,
data: doc.data(),
})
})
setMsgs(listings)
}
fetchMsg()
}, [])
const sendMessage = async (e) => {
e.preventDefault();
const docRef = await addDoc(collection(db, 'messages'), {
uid: user.uid,
displayName: user.displayName,
photoURL: user.photoURL,
text: value,
createdAt: serverTimestamp()
})
console.log(docRef)
setValue('')
}
if (loading) {
return <Spinner />
}
return (
<>
<div className='ch-wind'>
{msgs.map((msg) => (
<Message key={msg.id} msg={msg} style={{ backgroundColor: user.uid === msg.uid ? '#A32cc4' : '#a1045a' }} />
))}
</div>
<form className="ch-form" onSubmit={sendMessage}>
<textarea
value={value}
className='ch-form-text'
onChange={e => setValue(e.target.value)}
placeholder='Enter your message here'
/>
<button
className='ch-form-btn'
>
Send
</button>
</form>
</>
)
}
export default Chat
uj5u.com熱心網友回復:
通過使用useEffect()鉤子,我假設您想要實時獲取資料。Firestore 有一個你可以使用的實時監聽器。onSnapshot()您可以使用該方法收聽檔案。使用您提供的回呼的初始呼叫會立即使用單個檔案的當前內容創建檔案快照。然后,每次內容更改時,另一個呼叫會更新檔案快照。請參見下面的代碼:
useEffect(() => {
const messagesRef = query(collection(db, 'messages'), orderBy('timestamp', 'desc'));
onSnapshot(messagesRef, (snapshot) => {
// Maps the documents and sets them to the `msgs` state.
setMsgs(snapshot.docs.map(doc => ({
id: doc.id,
data: doc.data()
})))
})
}, [])
此外,正如@CDoe 所指出的,您應該使用Fieldname從方法中設定的相同,addDoc如您在上面的代碼中看到的那樣。
然后在渲染上,是這樣的:
{msgs.map((msg) => (
// By setting the `doc.data()` to the object `data`, you should access it by `msg.data.<object_key>`
<Message key={msg.id} msg={msg.data.text} style={{ backgroundColor: user.uid === msg.data.uid ? '#A32cc4' : '#a1045a' }} />
))}
我在代碼上留下了一些評論以便更好地理解它。
有關實時更新的更多資訊,您可以查看此檔案。
uj5u.com熱心網友回復:
在查詢中,您正在嘗試 orderBy timestamp。這不是您要在其中創建的欄位sendMessage。
當檔案中不存在您訂購的值時,它不會回傳。
也許你的意思是 orderyBycreatedAt值。
const q = query(
messagesRef,
orderBy('createdAt', 'desc')
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/453335.html
標籤:javascript 火力基地 谷歌云火库 反应钩子
上一篇:D3.JS地球上的點不隨地球旋轉
