React Hooks:如何在 useEffect 中设置状态? [英] React Hooks: How to setState inside useEffect?

查看:49
本文介绍了React Hooks:如何在 useEffect 中设置状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 firebase 获取数据并使用 useState 挂钩将检索到的数据设置为我的状态.我知道我的 API 调用正在工作,因为我可以从 firebase 记录数据,但是当我使用 setState() 时它并没有以我的状态结束,由于某种原因,我最终只有一个空数组处于状态.我错过了什么?

I am trying to fetch data from firebase and set the retrieved data to my state using the useState hook. I know my API call is working because I can log the data from firebase, yet its not ending up in my state when I use setState(), for some reason I end up with just an empty array in state. What am I missing?

const Collection = () => {
  const [ dreams, setDreams ] = useState([])

  useEffect(() => {
    const retrieveCollection = (userId) => {
      firebase.firestore().collection('Dreams')
        .where('user', '==', userId)
        .onSnapshot(snapshot => {
          let newDreams = snapshot.docChanges()
          newDreams.forEach(doc => {
            console.log(doc.doc.data())
            setDreams([...dreams, doc.doc.data()])
            console.log(dreams)
          })
        })
    }
    retrieveCollection('N25c9lKITZQ7JtPEZSrMX6uC7Ot2')
  }, [])

推荐答案

useState 很像它的对应物 setState 返回一个异步函数来设置状态.因此,在 setDreams 调用下方记录梦想不会给您任何结果.相反,您可以在 useEffect 外部登录以查看状态.

useState much like it's counterpart setState returns an asynchronous function to set the state. So logging dreams just below the setDreams call isn't going to give you any results. Instead you can log inside outside the useEffect to see the state.

但是 setDreams 在你的情况下是异步的还有另一个缺点,循环没有设置 dreams 足够快让你能够传播它,你可能会失去之间的更新,您可以使用功能性 setDreams 解决此问题.

But setDreams being async has another disadvantage in your case, the loop doesn't set dreams quick enough for you to be able to spread it, you might be loosing updates in between, you can fix this using the functional setDreams.

setDreams(prevDreams => [...prevDreams, doc.doc.data()])

或者更好的是,您可以在最后保存所有数据和 setState.

Or better still, you can save up all your data and setState at the very end.

const newDreamsState = newDreams.map(
  return doc.doc.data();
});
setDreams(newDreamsState);

这篇关于React Hooks:如何在 useEffect 中设置状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆