简体   繁体   中英

Props don't update value of state

I am passing value to child component Field:

<Field key = {field.fieldName} fieldName = {field.fieldName} value = {field.value} 
getModField={this._getModField.bind(this)} />

And in Field state should be updated by props:

constructor(props){
    super(props);

    this.state = {
        value: this.props.value,
        fieldName: this.props.fieldName
    };
}

I updated values should be shown in another field:

<div className = "form-group" key = {this.props.fieldName} >
    <input className="col-sm-2 control-label" name={this.props.value}
           defaultValue={this.state.value} onChange={this._handleChange.bind(this)} 
           ref={(input) => this._value = input} />
</div>

But in constructor of Field this line: value: this.props.value, doesn't update value . Only change of fieldName triggers change of value

在此处输入图片说明

I think it's somehow related to key prop. What can be problem here?

If I understand correctly, you want to update your component's state with latest props. The best place to do that is componentWillReceiveProps lifecycle method. You will get nextProps as an argument in this method based on which you can call setState with new values.

componentWillRecieveProps(nextProps) {
  this.setState({
    fieldName: nextProps.fieldName,
    value: nextProps.value
  });
}

additionally you can add a check to see if value and fieldName is changed in props or not. If not you can optimize to not re-render the Component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM