简体   繁体   中英

Does React rerenders component when a prop is changed

Suppose I have two components named Parent and Child . In Parent component I have a state named lastName which is passed to Child as a prop. Now after initial rendering of Child and Parent , if the lastName in Parent changed, will it cause Child component to rerender?

Yes, if you set the property via setState . However, re-render in React isn't something you should be afraid of, it's very efficient due to Virtual DOM usage.

In the child component you should use the following

shouldComponentUpdate(nextProps){
   return this.props.lastname !== nextProps.lastname
}

https://facebook.github.io/react/docs/component-specs.html#shouldComponentUpdate

After that, in the child component you might need to update the state. To achieve that you can use componentWillReceiveProps(nextProps)

componentWillReceiveProps(nextProps){
  this.setState({
    lastname: nextProps.lastname
  });
}

The Child component is only re-rendered when props lastName is being used in Child's render function and Parent use setState function to change lastName . Remember, React is one-way dataflow, if you want to re-render Child component right inside the Child, you must call an event which also trigger setState back to Parent component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM