码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-05-02 21:00:35      阅读:1295      评论:0      收藏:0      [点我收藏+]

标签:vstat   this   use   over   ike   message   ide   style   ber   

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

标签:vstat   this   use   over   ike   message   ide   style   ber   

原文地址:https://www.cnblogs.com/Answer1215/p/8981880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!