componentWillReceiveProps()被触发但它没有得到道具

问题描述 投票:0回答:1

在我的组件中,我使用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) 
    }
},
javascript reactjs
1个回答
1
投票
componentWillReceiveProps (nextProps) {
  if (nextProps.community !== this.props.community) {
    this.setState({community: nextProps.community})
  }
}

componentWillReceiveProps的参数是新的传入道具。 this.props.community是当前的道具并且是'旧'。无论你有什么异步,你可能还没有带回'社区'。

© www.soinside.com 2019 - 2024. All rights reserved.