gpt4 book ai didi

javascript - Props 不会更新 state 的值

转载 作者:行者123 更新时间:2023-12-03 04:55:22 24 4
gpt4 key购买 nike

我正在将值传递给子组件字段:

<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 的构造函数中这一行:值:this.props.value,不更新。只有 fieldName 的更改才会触发 value 的更改

enter image description here

我认为它与 key 属性有某种关系。这里可能有什么问题?

最佳答案

如果我理解正确,您想使用最新的 Prop 更新组件的状态。最好的地方是 componentWillReceiveProps 生命周期方法。您将获得 nextProps 作为此方法中的参数,您可以根据该参数使用新值调用 setState。

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

此外,您可以添加检查以查看 props 中的 value 和 fieldName 是否更改。如果没有,您可以优化以不重新渲染组件。

关于javascript - Props 不会更新 state 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42455674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com