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

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

问题描述

我正在尝试从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中设置setState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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