小编典典

如何使用生命周期方法getDerivedStateFromProps而不是componentWillReceiveProps

reactjs

看起来它将componentWillReceiveProps在即将发布的版本中完全淘汰,取而代之的是新的生命周期方法getDerivedStateFromPropsstatic
getDerivedStateFromProps()

经检查,它看起来像你现在无法作出直接比较this.propsnextProps,就像你可以在componentWillReceiveProps。有没有办法解决?

而且,它现在返回一个对象。我是否正确假设返回值本质上是this.setState

以下是我在网上找到的示例:状态源自props /
state

之前

class ExampleComponent extends React.Component {
  state = {
    derivedData: computeDerivedState(this.props)
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.someValue !== nextProps.someValue) {
      this.setState({
        derivedData: computeDerivedState(nextProps)
      });
    }
  }
}

class ExampleComponent extends React.Component {
  // Initialize state in constructor,
  // Or with a property initializer.
  state = {};

  static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.someMirroredValue !== nextProps.someValue) {
      return {
        derivedData: computeDerivedState(nextProps),
        someMirroredValue: nextProps.someValue
      };
    }

    // Return null to indicate no change to state.
    return null;
  }
}

阅读 267

收藏
2020-07-22

共1个答案

小编典典

有关删除的componentWillReceiveProps:你应该能够与组合来处理它的用途getDerivedStateFromPropscomponentDidUpdate,看到的阵营博客文章,例如迁移。是的,返回的对象getDerivedStateFromProps的状态更新与传递给的对象类似setState

万一您确实需要道具的旧值,可以随时使用以下内容将其缓存在状态中:

state = {
  cachedSomeProp: null
  // ... rest of initial state
};

static getDerivedStateFromProps(nextProps, prevState) {
  // do things with nextProps.someProp and prevState.cachedSomeProp
  return {
    cachedSomeProp: nextProps.someProp,
    // ... other derived state properties
  };
}

任何不影响状态的东西都可以放入componentDidUpdate,甚至还有一个getSnapshotBeforeUpdate用于底层的东西。

更新:要了解新的(和旧的)生命周期方法,react-lifecycle-
visualizer
软件包可能会有所帮助。

2020-07-22