gpt4 book ai didi

reactjs - React setState/getState 和异步

转载 作者:行者123 更新时间:2023-12-03 13:18:19 25 4
gpt4 key购买 nike

为什么 React 中没有异步 getState 函数?

文档告诉我们 setState 是异步的。很好,但这意味着我们无法安全地使用 this.state,并且我们还需要一个异步 getState 来尊重执行顺序。

据我了解,我们永远不应该使用 this.state 并使用这样的 getState 函数:

  getState(callback) {
this.setState((prevState) => {
callback(prevState) ;
});
}
...
this.getState((curState) => {
// we now can use the current state safely
}

我的思维方式有什么遗漏的吗?为什么 React 中不存在这样的函数?

--编辑--

正如我的一个 friend 告诉我的那样,这还不清楚,因为我不相信第一个答案,所以让我们分析一些代码:

simpleFunc() {
setState({ "counter" : 1 });
setState({ "counter" : 2 });
this.state.counter // => no garanty about the value
getState((curState) => { // ensure curState.counter is 2 });
}

这个简单的示例表明,我们不能在所有情况下直接使用 this.state,因为 setState 是异步的。

这是一个可以使用 getState 的反例: http://codepen.io/Epithor/pen/ZLavWR?editors=0010#0

简短回答:不好的做法,即使不确定 getState 是否给我们当前的

解决方法很简单,但我们可以分解一些函数并使用它们而不关心上下文,这一事实似乎很有趣,不是吗?

因此,当许多事件以特定顺序发生时,有些事件会更改状态,有些事件会读取状态:当事件使用 this.state 读取状态时,您如何确定良好的状态,因为所有更改都是异步的?

事实上一切都与时间有关:

T     : event 1, change state
T+1ms : event 2, change state
T+2ms : event 3, read state
T+3ms : event 4, change state

由于您无法预测事件 1 或 2 的 setState 究竟何时发生,如何保证事件 3 真正读取事件 2 中设置的状态?

简短回答:事件在 JS 堆栈中排队,而状态更改在内部 React 队列中排队。在交手之前,内部 React 队列已完全出栈。

最佳答案

一般来说,您绝对可以直接使用this.state。您永远不应该直接改变状态(this.state.foo = 0),而是在想要改变状态时使用setState

通常 setState 看起来像这样:

this.setState({
foo: 0
})

然后您就可以在 render() 函数中安全地使用 this.state.foo

但是需要注意的是,由于 setState 的异步特性,您无法保证在 之后能够立即访问 this.state setState 已被调用。

myFunc(baz) {
this.setState({
foo: baz + 1
})
console.log(this.state.foo) // not guaranteed
}

做得更好

myFunc(baz) {
const bazOne = baz + 1
this.setState({
foo: bazOne
})
console.log(bazOne)
}

或者使用setState函数的第二个参数,用作setState操作完成时执行的回调。在该回调中,您将可以访问更新后的状态,即 this.state:

myFunc(baz) {
this.setState({ foo: baz + 1 }, () => {
console.log(this.state.foo) // guaranteed in callback
});
}

参见:https://facebook.github.io/react/docs/react-component.html#setstate

关于reactjs - React setState/getState 和异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41896878/

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