[React] Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3相关的知识,希望对你有一定的参考价值。

The componentWillReceiveProps() method is being deprecated in future version of React (17). Many of us use this method day-to-day to check for incoming prop changes, store state, and to invoke side effects like logging or fetching data from a server.

In this lesson, we‘ll look at how to refactor an existing component that uses componentWillReceiveProps() to instead use getDerivedStateFromProps() and componentDidUpdate().

Additional Resources: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles

 

In short, 

componentWillReceiveProps: 

The new static getDerivedStateFromProps lifecycle is invoked after a component is instantiated as well as when it receives new props. It can return an object to update state, or null to indicate that the new props do not require any state updates.

should handle any local data changes:

  static getDerivedStateFromProps(nextProps, prevState) {
    const { number } = nextProps;

    return number === prevState.number
      ? { computedMessage: "Same number, try again!", number }
      : { computedMessage: null, number };
  }

 

componentDidUpdate:

hanlde any async update

  componentDidUpdate(nextProps) {
    const { number } = nextProps;
    if (this.state.computedMessage === null) {
      fakeServerRequest(this.props.number).then(result => {
        this.setState({ computedMessage: result });
      });
    }
  }

componentWillReceiveProps together with componentDidUpdate, this new lifecycle should cover all use cases for the legacy componentWillReceiveProps.

以上是关于[React] Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3的主要内容,如果未能解决你的问题,请参考以下文章

[React] Refactor a Stateful List Component to a Functional Component with React PowerPlug

[React] Refactor a connected Redux component to use Unstated

[Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose

react错误边界

react笔记1

react生命周期