在我拥有的组件中,我使用componentWillReceiveProps()以异步方式在组件中设置多个状态。父组件正在向此子项发送新道具。我的期望是,每当孩子获得新道具时,触发componentWillReceiveProps()并接收道具并相应地设置状态。事情是它有时工作正常,有时它不会!正如您在代码中看到的那样,我添加了一个if条件,因此只要this.props.community
获得值,它就会通过if块中的语句。但有时它不会,而this.props.community
仍然是undefined
!有人可以解释一下发生了什么以及如何解决它吗?
componentWillMount() {
this.componentWillReceiveProps(this.props);
},
componentWillReceiveProps(props) {
if(this.props.community && this.state.record){
if(...){
this.setState({....});
} else {
console.log("this.props.community = ", this.props.community) // undefined
console.log("this.state.record = ", this.state.record)
}
},
答案 0 :(得分:1)
componentWillReceiveProps (nextProps) {
if (nextProps.community !== this.props.community) {
this.setState({community: nextProps.community})
}
}
componentWillReceiveProps的参数是新的传入道具。 this.props.community是当前的道具,而且是“老了”。无论你有什么异步,你都可能没有回到社区'爱好。