Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

reactjs - why is componentWillReceiveProps deprecated?

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 have to deprecate componentWillReceiveProps.
What was the harm in making an ajax call inside componentWillReceiveProps? Once ajax call returns the value , I update the state thereby rerendering the component.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...