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

JavaScript

伽罗卡卡西

2020-03-11

看起来它将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;
  }
}

第779篇《如何使用生命周期方法getDerivedStateFromProps而不是componentWillReceiveProps》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
西门乐 2020.03.11

有关删除的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.03.11

正如我们最近发布的博客作出反应在绝大多数情况下,你并不需要getDerivedStateFromProps在所有

如果只想计算一些派生数据,请执行以下任一操作:

  1. 就在里面做 render
  2. 或者,如果重新计算的成本很高,请使用类似的备忘录助手memoize-one

这是最简单的“之后”示例:

import memoize from "memoize-one";

class ExampleComponent extends React.Component {
  getDerivedData = memoize(computeDerivedState);

  render() {
    const derivedData = this.getDerivedData(this.props.someValue);
    // ...
  }
}

查看博客文章的此部分以了解更多信息。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android