Redux不会立即更新状态

时间:2018-07-09 13:42:23

标签: reactjs redux react-redux

我对Redux有问题,甚至更多不是问题,而是误解。 如果我确实调度了一个函数并在存储中写入了一个新值,那么我将无法立即从存储中获取一个新值。

示例:

    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()中,则会出现一个新状态。

我很高兴听到关于为什么以及如何向商店中写入值并立即从中读取值的解释。

2 个答案:

答案 0 :(得分:3)

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

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

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

(请注意,该组件已在回调之前重新呈现。)

如果您有逻辑,则需要在“外部”状态更新(例如Redux)之后运行,然后再执行componentDidUpdate,但这也可能表示体系结构问题。

答案 1 :(得分:1)

我不知道这是不是一个好习惯,但这行得通

onButtonIncrementClick: () => new Promise(resolve => {
      dispatch({ type: 'INCREMENT' });
      resolve()
    })

...

this.props.onButtonIncrementClick().then(() => {
  console.log('in func: after', this.props.count);
})
相关问题