【问题标题】:componentWillReceiveProps on react does not pass the current property when ever it triggersreact 上的 componentWillReceiveProps 在触发时不会传递当前属性
【发布时间】:2017-05-17 07:35:58
【问题描述】:

大家好,我是新来的反应 我正在使用从父组件的状态传递属性的反应组件,我不确定为什么每当我从父组件触发和事件时都会收到未定义的属性错误

您可以在这里访问代码@https://codepen.io/private_ryan/pen/RVBdpO?editors=0011#live-view显示控制台并点击编辑按钮

SampleTable 组件

 constructor(props, context) {
    super(props);
    this.state = { UPD:[] };
}

updateRow(x) {
    var array = this.state.TRs;
    var index = array.findIndex(e => e.id == x);
    this.setState({
        UPD: this.state.TRs[index]
    });
}

render() {
    return (<AddFormData onAdd={ this.onAddForm } 
               upd={ this.state.UPD } 
               updcan={ this.cancelUpd } 
               propUpd= { this.propcessUpd } />
             <button onClick={ this.updateRow} value={ some.id } >click me</button>
     );
}

AddFormData 组件

 constructor(props) {
    super(props);
    this.state = { textName: '', textArea: '' };
}

componentWillReceiveProps(){
    console.log( this.props ) // undefined no props when first click
    // set the state here
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    新的道具作为函数的参数被接收:

    componentWillReceiveProps(nextProps)

    https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

    【讨论】:

    • @RED 请在解决您的问题时投票和/或接受答案。
    【解决方案2】:

    componentWillReceiveProps 将在您对父组件中的 props 值进行任何更改时被调用,新值将作为参数传递,并且在此生命周期方法之后 this.props 将得到更新,因此如果您在其中执行 console.log(this.props) 它将记录以前的值而不是新的值。

    使用这个:

    componentWillReceiveProps(newProps){
        console.log(this.props.upd.id, newProps)
    }
    

    检查working example

    【讨论】:

      猜你喜欢
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多