想让父组件的state 更新的时候。子组件也根据这个状态更新
父组件中:
this.state={
show:true
}
用 show={this.state.show} 把父组件的状态传进去
<WrappedQueryForm show={this.state.show}/>
子组件中接收这个参数:
componentDidMount() {
console.log(this.props.show)
}
但是发现只有第一次的时候接收到了,父组件state改变,子组件并没有实时的更新
子组件componentDidMount只会被调用一次,所以没法在这个方法中根据新的props更新你的state,非要这么做的话,应该在子组件的componentWillReceiveProps(nextProps)这个方法中做。
子组件中接收参数改为:
componentDidMount() {
console.log(this.props.show)
}
componentWillReceiveProps(nextProps) {
if (nextProps.show === "true") {
//do something
}
}
记得要用nextProps奥!
备注:componentDidMount 在初始化render之后只执行一次,在这个方法内,可以访问任何组件,componentDidMount()
方法中的子组件在父组件之前执行
componentWillReceiveProps:
当props
发生变化时执行,初始化render
时不执行,在这个回调函数里面,你可以根据属性的变化,通过调用this.setState()
来更新你的组件状态,旧的属性还是可以通过this.props
来获取,这里调用更新状态是安全的,并不会触发额外的render
调用