![](/img/trans.png)
[英]Changing parent's state from child, but the props of the child don't update
[英]Props don't update value of state
我正在将值传递给子组件字段:
<Field key = {field.fieldName} fieldName = {field.fieldName} value = {field.value}
getModField={this._getModField.bind(this)} />
并且在Field状态下应通过props更新:
constructor(props){
super(props);
this.state = {
value: this.props.value,
fieldName: this.props.fieldName
};
}
我更新的值应显示在另一个字段中:
<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>
但是在Field的构造函数中,以下行: value: this.props.value,
不更新value
。 仅更改fieldName会触发value
更改
我认为这与key
道具有关。 这里有什么问题?
如果我理解正确,则希望使用最新的道具来更新组件的状态。 最好的方法是componentWillReceiveProps
生命周期方法。 在此方法中,您将获得nextProps作为参数,基于该参数可以使用新值调用setState。
componentWillRecieveProps(nextProps) {
this.setState({
fieldName: nextProps.fieldName,
value: nextProps.value
});
}
另外,您可以添加检查以查看value和fieldName是否在prop中进行了更改。 如果没有,您可以进行优化以不重新渲染组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.