当改变道具时,React是否重新渲染组件

时间:2016-08-03 10:17:55

标签: javascript reactjs

假设我有两个名为ParentChild的组件。在Parent组件中,我有一个名为lastName的状态,作为道具传递给Child。现在,在初始呈现ChildParent后,如果lastName中的Parent发生了更改,是否会导致Child组件重新呈现?

3 个答案:

答案 0 :(得分:0)

是的,如果您通过setState设置了该属性。但是,在React中重新渲染并不是你应该害怕的东西,由于Virtual DOM的使用,它非常有效。

答案 1 :(得分:0)

在子组件中,您应该使用以下

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

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

之后,在子组件中,您可能需要更新状态。为此,您可以使用componentWillReceiveProps(nextProps)

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

答案 2 :(得分:0)

只有在Child的渲染功能中使用道具lastName并且使用setState函数更改lastName时才会重新渲染子组件。请记住,React是单向数据流,如果要在Child内部重新呈现Child组件,则必须调用一个事件,该事件也会触发setState回到父组件