SoFunction
Updated on 2025-04-07

How to change the way props are listened to in react

React listener props changes

componentWillReveiceProps

Previously usedcomponentWillReveicePropsTo 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.0Has 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 isUNSAFEInsecure.

UNSAFE_componentWillReceiveProps

How to use andcomponentWillReveicePropsThe 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: 
  }
}

HerecurSthis defined in the subcomponentstatevariable onsthis the value passed in to the child component in the parent component, andreturnIn 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 timepropsHas 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.echartsAs a component, the line chart is rendered later when the incoming value changes.echartsDrawing 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.