What is the sequence of actions when using promises in useEffect hook in React?

前端 未结 1 882
忘掉有多难
忘掉有多难 2021-01-25 20:26

In the code below I was expecting that inside the useEffect hook console.log procedure will log the list of the tickets fetched by getAllTickets function because list of the tic

1条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 20:54

    It's not that there's a sequencing issue. It's that the function logging the tickets value is logging an old value.

    Your useEffect callback is created each time your component function is called, but because your dependency array is empty, only the first of those functions is ever called by useEffect. That first function closes over the tickets constant for the call to your component function that created the callback (the first call), in which tickets is an empty array. So although setTickets updates your state item, which will cause your component function to be called again, your useEffect callback (or more accurately, the callbacks it creates) continue to use the old value.

    If you want to see the updated array, you can use res:

    React.useEffect(() => {
      getAllTickets()
        .then((res) => {
              const ticketsReceived = [...res]; // Why the shallow copy?
              setTickets(ticketsReceived);
              console.log(ticketsReceived);
         })
        .catch((e) => console.log(e));
    }, []);
    

    0 讨论(0)
提交回复
热议问题