我对 Redux 有问题,更可能不是问题而是误解。
如果我在函数中进行分派并在存储中写入新值,那么我无法立即从存储中获取该函数的新值。
Example:
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 https://codesandbox.io/s/yk1jzjv6l1
我怀疑这与异步有关,因为如果我将状态包装在setTimeout()
一个新的状态到来了。
我很高兴听到关于为什么以及如何将值写入商店并立即从中读取它们的解释。
setState不同步 https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous,无论是你还是 Redux 更新它。
正如你所说,这是一个误解。当您直接更新它时,您可以提供要执行的回调,例如,
setState({ foo }, () => somethingWith(this.state));
(请注意,该组件已在回调之前重新渲染。)
如果您有需要在“外部”状态更新(例如 Redux)后运行的逻辑,那么有componentDidUpdate
,但这也可能表明存在架构问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)