[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.

转载于:https://www.cnblogs.com/Answer1215/p/8981880.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值