假设我有两个名为Parent
和Child
的组件。在Parent
组件中,我有一个名为lastName
的状态,作为道具传递给Child
。现在,在初始呈现Child
和Parent
后,如果lastName
中的Parent
发生了更改,是否会导致Child
组件重新呈现?
答案 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
回到父组件