React listener props changes
componentWillReveiceProps
Previously usedcomponentWillReveiceProps
To realize communication during component update phase
class xxx extends Component { /** Omit irrelevant code **/ componentWillReceiveProps (nextProps) { if ( !== ) { // The sth value changes next step } } }
at this timeReact13.16.0
Has been changed toUNSAFE_componentWillReceiveProps
It can be seen from the name that the official does not recommend using this hook, but you have to use it, so I will give you a capital prefix to tell you that this hook isUNSAFE
Insecure.
UNSAFE_componentWillReceiveProps
How to use andcomponentWillReveiceProps
The same is true, but the official has added a prefix to tell you to try not to use it.
As for why it was abandoned, it was because
Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. Make sure to compare the current and next values if you only want to handle changes.
As long as the parent component causes your component to re-reender, your component will trigger the componentWillReceiveProps method, even if the props received by your component have not changed.
Like me, if the official does not recommend it, I will definitely look for an alternative method.
Since the official canceled a method, a more recommended method will naturally be given.
getDerivedStateFromProps
// Assign the value to the current component's state variable after props changesstatic getDerivedStateFromProps (nextProps, prevState) { return { curSth: } }
HerecurSth
is defined in the subcomponentstate
variable onsth
is the value passed in to the child component in the parent component, andreturn
In the future, the value passed in by the parent component will be assigned to the corresponding variable of the child component, that is, at this timeprops
Has changed
What if the next step is performed at this time?
componentDidUpdate () { // When curSth is reassigned by sth, you can perform the operation after props is changed here.}
Specific practical cases have also been applied in a previous article.echarts
As a component, the line chart is rendered later when the incoming value changes.echarts
Drawing of
→_→Use echarts in react and implement tooltip loop carousel
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.