gpt4 book ai didi

javascript - 如何在 React 中处理对 setState 的异步调用?

转载 作者:行者123 更新时间:2023-11-30 09:33:51 25 4
gpt4 key购买 nike

我有一个方法可以通过复制值然后更新状态来切换状态中的 bool 值:

toggleSelected = () => {
let selected = this.state.lists.selected;
selected = !selected;
this.setState({
// update state
});
};

我有另一个方法,由 onClick 处理程序触发,调用 toggleSelected 两次:

switchList = (listName) => {
const currList = this.getCurrentList();
if(listName === currList.name) return;
this.toggleSelected(listName);
this.toggleSelected(currList);
};

但是,在第二次调用运行时,状态似乎并未从第一次调用完成设置;如果我在第二次调用时设置超时,它会正常工作。

正确的做法是什么?

最佳答案

@SLaks 建议的替代方法(有时很有用)是使用 setState(new_state, callback) 方法。一旦状态更新并“可见”,回调将运行。

一般情况下,setState 不会立即改变状态,以便在this.state 中可见。来自docs

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

关于javascript - 如何在 React 中处理对 setState 的异步调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44726453/

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