简体   繁体   English

为什么在回调函数中反应状态(数组)为空? 为什么不使用来自外部范围的更新值?

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

This problem has stumped me.这个问题把我难住了。 I'm trying to append values to existing array, but inside the onmessage callback, state is an empty array every time the callback is called!我正在尝试将值附加到现有数组,但在 onmessage 回调中,每次调用回调时 state 都是一个空数组! I'm not able to figure out why!我无法弄清楚为什么! Any help is appreciated.任何帮助表示赞赏。

  • React version: 16.12.0反应版本:16.12.0
  • Node version: 10.16.3节点版本:10.16.3

Code snippet:代码片段:

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} />
}

Thanks谢谢

Setting a state is async in nature.设置状态本质上是异步的。 Your console.log will always print the previous value of state.您的 console.log 将始终打印 state 的先前值。 You can use useEffect to get the updated value of state everytime it changes -您可以使用 useEffect 在每次更改时获取 state 的更新值 -

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

Try using the state updater function.尝试使用状态更新器功能。 If you pass a function to setState, React will call it with the actual state:如果你将一个函数传递给 setState,React 将使用实际状态调用它:

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

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

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