【问题标题】:Capture state value after multiple setState in ReactJS在 ReactJS 中多次 setState 后捕获状态值
【发布时间】:2020-01-04 21:44:00
【问题描述】:

我的 React 组件中有几个方法,所有这些方法都会修改状态:

class Abc extends React.Component {

    state = {
        f1 : 'f1',
        f2 : 'f2',
        f3 : 'f2',
        dynamicValue : 'some initial value',
    }

    func1 = () => { 
        //..do some work
        this.setState({ f1 : someValue1})
    }

    func2 = () => { 
        //..do some work
        this.setState({ f2 : someValue2})
    }

    func3 = () => { 
        //..do some work
        this.setState({ f3 : someValue3})
    }

    doWorkAfterAllSetStateIsComplete = () => {
        const val = this.state.dynamicValue;
        // I get stale state here
    }

    doWork = () => {
        func1();
        func2();
        func3();
        doWorkAfterAllSetStateIsComplete();
    }
}

如果我像这样在setTimeout 中调用doWorkAfterAllSetStateIsComplete,我会得到更新的状态。

setTimeout(() => {
    doWorkAfterAllSetStateIsComplete();
    // this.state.dynamicValue is updated here.
}, 0)

我知道这是因为setStateasyncsetTimeout 在JavaScript 的下一个“滴答”中调用doWorkAfterAllSetStateIsComplete,所以我在doWorkAfterAllSetStateIsComplete 中获得了更新的状态值。但这对我来说似乎有点 hacky。还有其他方法可以实现吗?

【问题讨论】:

标签: reactjs


【解决方案1】:

您可以使您的doWork 函数async 等待 setStates 完成,然后在函数中使用它们的值:

doWorkAfterAllSetStateIsComplete = () => {
  console.log(this.state);
}

doWork = async () => {
    await this.func1();
    await this.func2();
    await this.func3();
    this.doWorkAfterAllSetStateIsComplete();
}

您也可以使用componentDidUpdate() 来检查状态是否发生了变化:

componentDidUpdate(prevProps, prevState){
    if(prevState.f1 !== this.state.f1 && prevState.f2 !== this.state.f2 && prevState.f3 !== this.state.f3)
        this.doWorkAfterAllSetStateIsComplete();
}

【讨论】:

  • 这在技术上是不正确的,因为setState 不返回承诺,并且在示例代码中也没有等待。您需要承诺并等待setState 才能使这个答案起作用。检查stackoverflow.com/questions/53409325/…
【解决方案2】:

您可以像这样对componentDidUpdate 中的状态变化做出反应:

componentDidUpdate(prevProps, prevState) {
  if (this.state.f3 === someValue3) {
    doWorkAfterAllSetStateIsComplete();
  }
}

或者,您可以在 setState 中提供回调以在完成时运行。为了等待所有你可以把它变成一个Promisepromisify 并等待所有这些承诺。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 2017-09-05
    • 2019-11-24
    • 2020-07-07
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多