首页 > 解决方案 > 状态不变

问题描述

我正在开发一个 react js 应用程序并做一些基本的事情,设置新值时状态似乎没有改变。这是代码:

pageChange = currentPage => {
    const newState = Immutable.merge(this.state, 
        { 
            page: currentPage
        }, 
        { deep: true });
    this.setState(newState);

    console.log(this.state);    // the page property remains the same
    console.log(newState);      // the page property has the new value, the currentPage

    this.openPreview();
}

在代码中,当前状态未被设置,但 newState 具有新值。为什么?

标签: reactjs

解决方案


您可以利用 setState() 的第二个参数:

pageChange = currentPage => {
  ...
  this.setState(
    newState,
    () => this.openPreview() // This occurs -after- setState has finished
                             // ensuring openPreview() works as you expect
  );
}

推荐阅读