How to check what props changed in componentWillReceiveProps
Answer a question
Is there a way to check what props changed (without storing old props elsewhere) inside componentWillReceiveProps ?
i.e.
componentWillReceiveProps (newProps) {
if( /* newProps.profileImage is different to previous props */ ) /* do stuff */
}
Answers
Note that the function componentWillReceiveProps is now deprecated. Quoting the official documentation:
If you used
componentWillReceivePropsfor re-computing some data only when a prop changes, use a memoization helper instead.
This refers to the case where the your check inside componentWillReceiveProps was to avoid unnecessarily recomputing the same thing many times. In the linked blog post, it suggests caching the result of the expensive function so that it can be looked up, rather than recomputed. This can be done using a helper such as memoize-one.
If you used
componentWillReceivePropsto “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.
Again, the linked blog post describes this in more detail, but in a nutshell:
- The "fully controlled" component refers to a functional component with no state (the parent component is responsible for handling the state).
- The "fully uncontrolled" alternative is one that only uses the
propsto set the initial state, and then ignores all further changes to the props.
In very rare cases, you might want to use the
getDerivedStateFromPropslifecycle as a last resort.
This function receives (props, state) and returns any changes to the state before render is called, giving you the control to do whatever you want.
Original answer, for older versions of React
At the point in time that this lifecycle method is called, this.props refers to the previous set of props.
To compare a single property foo on the the new props with the same property on the old ones, you can just compare newProps.foo with this.props.foo. So in your example:
componentWillReceiveProps (newProps) {
if( newProps.profileImage !== this.props.profileImage ) /* do stuff */
}
更多推荐
所有评论(0)