Reputation: 65
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?
Upvotes: 0
Views: 115
Reputation: 2254
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.
Upvotes: 1