gpt4 book ai didi

javascript - 为什么回调函数中的react state(array)为空?为什么它不使用外部范围的更新值?

转载 作者:行者123 更新时间:2023-12-02 22:18:01 25 4
gpt4 key购买 nike

这个问题难倒了我。我试图将值附加到现有数组,但在 onmessage 回调中,每次调用回调时状态都是一个空数组!我不明白为什么!如有任何帮助,我们将不胜感激。

  • react 版本: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} />
}

谢谢

最佳答案

尝试使用状态更新器功能。如果你将一个函数传递给 setState,React 将使用实际状态调用它:

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

关于javascript - 为什么回调函数中的react state(array)为空?为什么它不使用外部范围的更新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59322030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com