简体   繁体   English

如何为一系列已履行的承诺设置状态

[英]how to setState for an array of fulfilled promises

In my react app, I am retrieving some data from firebase , but when I try to store the items in my state it stores only the first item of the fulfilled promises ,在我的反应应用程序中,我正在从 firebase 检索一些数据,但是当我尝试将项目存储在我的状态时,它仅存储已履行承诺的第一项,

const HomePage = (props) => {
  const [events ,setEvents] = React.useState([])
const fetchGames=async()=>{
    const DB =await db.collection('game').get()

    DB.docs.forEach(item=>{
      setEvents([...events,item.data()])
      console.log(item.data()); // Here shows all the items that stored in my firebase collection
     })
    }
    
    useEffect(()=>
    {
      fetchGames()
    }, [])
return(
<div>
{
     events.map((event)=>
        (
          <div>
            {event.home_color}
          </div>

        )
        )
    }
</div>
)

Eventually the events state will display only one item , unlike in the console log which displayed all the items , how to fix this?最终事件状态将只显示一个项目,不像控制台日志中显示所有项目,如何解决这个问题?

React state is not synchronous . React 状态不是synchronous的。 So updating state in a for loop does not guarantee every iteration you will get an updated state.因此,在 for 循环中更新状态并不能保证每次迭代都会获得更新的状态。

You can prepare the final object in the forEach & then update state once it has finished.您可以在forEach中准备最终对象,然后在完成后更新状态。 Something like -就像是 -

const fetchGames=async()=>{
    const DB =await db.collection('game').get()
    const eventsFromDb = [];
    DB.docs.forEach(item=>{
      // update eventsFromDb array here 
    })
    // set state here
    setEvents(eventsFromDb);
}

Repeatedly calling setEvents in your forEach loop does not allow for the state to actually be updated because the React useState hook is not synchronous.在 forEach 循环中重复调用setEvents不允许实际更新状态,因为 React 的 useState 钩子不是同步的。

You could do something like this:你可以这样做:

setEvents([ ...events, ...DB.docs.map(item => item.data())])

Assuming the data() method isn't async - sorry I don't know Firebase.假设data()方法不是异步的 - 抱歉我不知道 Firebase。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM