這個(gè)問(wèn)題,困擾了我,特此記錄。
子組件顯示父組件傳來(lái)的props 做更新有 以下2種常用方式:
1.直接使用
class Child extends Component {
render() {
return <div>{this.props.someThings}</div>
}
}
這種方式可以直接在子組件中使用,方便快捷,父組件的更新的數(shù)據(jù)直接影響子組件的值。
2.轉(zhuǎn)換成自己的state
class Child extends Component {
constructor(props) {
super(props);
this.state = {
someThings: props.someThings
};
}
componentWillReceiveProps(nextProps) {
this.setState({someThings: nextProps.someThings});
}
render() {
return <div>{this.state.someThings}</div>
}
}
自己在構(gòu)造函數(shù)中初始化一個(gè)值,在將 status 通過(guò) componentWillReceiveProps 生命周期方法 更新
自己喜歡用的是第二種,看起來(lái)易維護(hù),代碼結(jié)構(gòu)清晰
但是,我遇到一個(gè)問(wèn)題,是在渲染第一次是正常的,之后怎么也不做渲染了
后面發(fā)現(xiàn)了,是無(wú)意間使用了 提升react加載性能的 shouldComponentUpdate方法,該方法會(huì)阻止 states 的重新渲染