【问题标题】:How to properly return updated state when using getDerivedStateFromProps lifecycle method?使用 getDerivedStateFromProps 生命周期方法时如何正确返回更新状态?
【发布时间】:2021-09-29 20:47:46
【问题描述】:

例如我们有这样的状态:

state = { hasSomething: true, anotherKey: '', ... }

我们应该只更新“hasSomething”:

static getDerivedStateFromProps(nextProps) {
        if (nextProps.accessKey === 'admin') {
            return {
                hasSomething: false,
            };
        }
        return null;
    }

当我们返回新状态时,我们是否需要破坏 prevState? 比如这样:

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.accessKey === 'admin') {
        return {
            ...prevState,
            hasSomething: false,
        };
    }
    return null;
}

或者我们不需要它? 我检查了console.log(this.state),如果我没有破坏prevState,它会返回整个本地状态。

我在官方反应文档中找不到此信息:(

附:这个逻辑只是一个例子:)

【问题讨论】:

    标签: javascript reactjs react-lifecycle


    【解决方案1】:

    官方文档说It should return an object to update the state, or null to update nothing.https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops)。当您只返回部分状态时,它不会清除状态,因此它的工作方式类似于setState (https://reactjs.org/docs/react-component.html#setstate)。 setState 文档说 You may optionally pass an object as the first argument to setState() instead of a function. This performs a shallow merge of stateChange into the new state.,所以你不需要破坏之前的状态。

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2018-09-12
      • 2020-05-02
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多