简体   繁体   English

更改道具后,React会重新渲染组件吗

[英]Does React rerenders component when a prop is changed

Suppose I have two components named Parent and Child . 假设我有两个组件,名为ParentChild In Parent component I have a state named lastName which is passed to Child as a prop. Parent组件中,我有一个名为lastName的状态,该状态作为道具传递给Child Now after initial rendering of Child and Parent , if the lastName in Parent changed, will it cause Child component to rerender? 现在的初始渲染后的ChildParent ,如果lastNameParent改变,它会导致Child组件重新呈现?

Yes, if you set the property via setState . 是的,如果您通过setState设置属性。 However, re-render in React isn't something you should be afraid of, it's very efficient due to Virtual DOM usage. 但是,React中的重新渲染并不是您应该担心的事情,由于使用了虚拟DOM ,它非常有效。

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 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)

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 . 仅当在child的渲染函数中使用道具lastName且Parent使用setState函数更改lastName时,才重新渲染Child组件。 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 记住,React是单向数据流,如果您想在Child内部重新渲染Child组件,则必须调用一个事件,该事件还将触发setState回到Parent组件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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