why is componentWillReceiveProps deprecated?

前端 未结 2 1036
臣服心动
臣服心动 2020-12-08 20:01

I read through https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change . I am still not able to understand why did they h

相关标签:
2条回答
  • 2020-12-08 20:39

    My understanding is that if the componentWillReceiveProps() method is being invoked then some properties of the component has been changed and that component should be informed and potentially re-rendered again.

    Having ajax call inside of the componentWillReceiveProps() might break that flow.

    My gut feeling is that we are gently guided to make ajax calls outside of the components and pass all the results of those ajax calls through properties. It makes your components very clean and testable.

    0 讨论(0)
  • 2020-12-08 20:45

    componentWillReceiveProps is a synchronous hook. Calling asynchronous function like data fetching inside this hook will need to render in between when the new props are set and when data has finished loading.

    But the getDerivedStateFromProps is an asynchronous hook won't require any additional render. Thus, componentWillReceiveProps is being deprecated in favor of the following reason:

    1. Use getDerivedStateFromProps
    2. Or, use componentDidUpdate

    Which won't give you unnecessary renders. Note that getDerivedStateFromProps is used only in rare case though. So, I suggest you to use componentDidUpdate hook as far as possible.


    The similar things happen when comparing componentWillMount and componentDidMount. Use componentDidMount whenever you need operate async operation and forget componentWillMount at all condition. More explanation about componentDidMount is here in my another post.

    0 讨论(0)
提交回复
热议问题