[英]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: 并且在Field状态下应通过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
. 但是在Field的构造函数中,以下行:
value: this.props.value,
不更新value
。 Only change of fieldName triggers change of value
仅更改fieldName会触发
value
更改
I think it's somehow related to key
prop. 我认为这与
key
道具有关。 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. 最好的方法是
componentWillReceiveProps
生命周期方法。 You will get nextProps as an argument in this method based on which you can call setState with new values. 在此方法中,您将获得nextProps作为参数,基于该参数可以使用新值调用setState。
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. 另外,您可以添加检查以查看value和fieldName是否在prop中进行了更改。 If not you can optimize to not re-render the Component.
如果没有,您可以进行优化以不重新渲染组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.