【问题标题】:ComponentWillReceiveProps not triggeredComponentWillReceiveProps 未触发
【发布时间】:2018-08-16 22:10:43
【问题描述】:

我是 React 世界的新手。我在执行编辑操作时被生命周期方法卡住了。

即使改变了 props 也不会触发 componentWillReceiveProps 方法。

这是我的代码示例。

      this.intialState = {
                      name:'',
                      code:'',
                      };
    this.state = this.intialState;




  componentWillReceiveProps(nextprops){
      this.setState({
        name:nextprops.KaraikarEdit.name,
        code:nextprops.KaraikarEdit.code
     })
    }



render() {


 return (
                <div className="form-group">
                <input type= "text"  className="form-control" value={this.state.name}  placeholder="Enter Name" name="name"   onChange = {this.onhandleChange} />
                </div>

                <div className="form-group">
                <input type= "text"  className="form-control" value={this.state.code}  placeholder="Enter Code" name="code"   onChange = {this.onhandleChange} />
                </div>

);
}

 const mapStateToProps = (state) => {
    return {

             KaraikarEdit: state.KaraikarDetails.editdata
         }
  }


export default connect(mapStateToProps)(KaraikarMasterAdd);

我在 KaraikarEdit 中收到了新道具。但是 componentWillReceiveProps 生命周期方法没有被触发。

我知道 componentWillReceiveProps 在第一次渲染时没有被调用。所以我使用了 componentDidMount 方法,在这个方法中我调度了一个对该组件无用的操作。然后 componentWillReceiveProps 正在工作。

我应该使用 componentDidMount 还是 componentWillMount 方法来使用 componentReceiveProps 方法?如果是这样,在 componentDidMount 方法中包含什么?

【问题讨论】:

  • 是的。我发送了一个操作并使用 editdata 更新了我的商店。只有从州我得到了道具。但是仍然没有触发 componentWillReceiveProps。
  • 你如何确定你在 karaikarEdit 中收到了新道具? componentwillreceiveprops 是一个仅在更新场景中触发而不在初始渲染中触发的事件(如您所说)。因此,如果您的组件在初始渲染后发送了新的道具,它肯定可以工作
  • 当然。我在 KaraikarEdit 中收到了新道具。
  • 您如何确认您在 karaikarEdit 中收到了 newProps?
  • @arthy,你的应用是做什么的?

标签: reactjs react-redux


【解决方案1】:

如果你想在安装时设置组件state,你应该使用componentDidMountcomponentWillReceiveProps 未在初始渲染时调用。然后,为了处理更新,您可能希望在呈现更新的标记之前使用componentWillUpdate 设置新状态(因为它基于组件状态)。

但是!正如我在您的方法中看到的那样 - 您不必要地将商店状态复制到组件状态。 您可以在render 函数中使用this.props在这种方法中,您的实现中将不需要componentWillReceiveProps

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多