![](/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.