![](/img/trans.png)
[英]How to execute firebase cloud function one minute after an event occurred?
[英]How to execute function only after value is loaded?
我正在使用 firebase 在使用 useEffect 加載頁面后立即執行代碼。
我在 Redux 中有一個 state 用戶,從 null 到實際用戶信息到 go 需要幾秒鍾。
我的問題是代碼會立即觸發,我不確定如何讓它等到用戶信息加載完畢。
由於“user.email”的“null”值,在代碼中顯示錯誤
const {user} = useSelector(state=>state.user)
const [myGames, setMyGames] = useState([])
useEffect(()=> {
const unsubscribe = db.collection("games")
.where("username", "==", user.email)
.onSnapshot(snapshot=> setMyGames(snapshot.docs.map(doc=> doc.data().game_title)))
return ()=> {
unsubscribe()
}
}, [])
當你給useEffect一個空數組作為第二個參數時,你是在告訴它在第一個組件渲染之后運行一次。 這不會等待 state 更改。 為了將 useEffect 綁定到一個數據點,通過在給定的數組中傳遞它來綁定它。
注意:這將在每次更新用戶時觸發效果!
例子:
const {user} = useSelector(state=>state.user)
const [myGames, setMyGames] = useState([])
useEffect(()=> {
if(user.email !== null){
const unsubscribe = db.collection("games")
.where("username", "==", user.email)
.onSnapshot(snapshot=> setMyGames(snapshot.docs.map(doc=>
doc.data().game_title)))
}
return ()=> {
unsubscribe()
}
}, [user])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.