簡體   English   中英

為什么在回調函數中反應狀態(數組)為空? 為什么不使用來自外部范圍的更新值?

[英]Why is react state(array) empty inside callback function? Why is it not using the updated value from outer scope?

這個問題把我難住了。 我正在嘗試將值附加到現有數組,但在 onmessage 回調中,每次調用回調時 state 都是一個空數組! 我無法弄清楚為什么! 任何幫助表示贊賞。

  • 反應版本:16.12.0
  • 節點版本:10.16.3

代碼片段:

const Example = () => {

  const [state, setState] = useState([]);

  useEffect(() => {
    axios.get("/data").then((resp) => setState(resp.data)); // Array of length of 50

    const eventSource = new EventSource("/event");

    eventSource.onmessage = (e) => {
      console.log(state); // [] - Empty array
      const data = JSON.parse(e.data);
      setState([data, ...state]); // End result - state is array of length 1
    }

    return () => eventSource.close();

  }, []);

  console.log(state); // Array of length 50

  // Table rendered with 50 elements
  return <Table data={state} />
}

謝謝

設置狀態本質上是異步的。 您的 console.log 將始終打印 state 的先前值。 您可以使用 useEffect 在每次更改時獲取 state 的更新值 -

useEffect(() => { console.log("value of state is", state)}, [state] // dependancy array//)

嘗試使用狀態更新器功能。 如果你將一個函數傳遞給 setState,React 將使用實際狀態調用它:

setState(actualState => {
    return [data, ...actualState]
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM