gpt4 book ai didi

javascript - Redux 不会立即更新状态

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

我对 Redux 有疑问,更可能不是问题而是误解。如果我在函数中进行分派(dispatch)并在存储中写入新值,那么我无法立即从存储中获取该函数的新值。

示例:

    testFunc = () => {
console.log('in func: before', this.props.count); //state store
this.props.onButtonIncrementClick(); //dispatch a new state in the store
console.log('in func: after', this.props.count); //get the old state store
};

实例: https://codesandbox.io/s/yk1jzjv6l1

enter image description here

我怀疑这与异步有关,因为如果我将状态包装在 setTimeout() 中,就会出现一个新状态。

我很高兴听到关于为什么以及如何将值写入存储并立即从中读取它们的解释。

最佳答案

setState is not synchronous ,无论是你还是 Redux 更新它。

正如你所说,这是一个误解。当您直接更新它时,您可以提供要执行的回调,例如,

setState({ foo }, () => somethingWith(this.state));

(请注意,组件在回调之前已重新渲染。)

如果您有需要在“外部”状态更新(例如 Redux)后运行的逻辑,那么可以使用 componentDidUpdate,但它也可能表明存在架构问题。

关于javascript - Redux 不会立即更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51247040/

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