在我的 React 应用程序(版本 15.5.4)中,我的一个组件中的输入字段收到以下警告:
Warning: 'value' prop on 'input' should not be null. Consider using the empty string to clear the component or 'undefined' for uncontrolled components.
参考以下jsx:
<label>Description<br />
<input
type="text"
name="description"
value={this.state.group.description}
onChange={this.handleChange}
maxLength="99" />
</label>
但我对此感到困惑,因为 this.state.group.description
的值在我的构造函数中设置为 ""
:
this.state = {
"group": {
"name": "",
"description": ""
}
}
让我更加惊愕的是,另一个输入字段引用了 this.state.group.name
,但没有发出警告:
<label>Name *<br />
<input
type="text"
name="name"
value={this.state.group.name}
onChange={this.handleChange}
maxLength="99"
required="required"
autoFocus />
</label>
我在这里错过了什么吗?据我所知,我已将这两个值的初始状态设置为空字符串,并在两个输入字段中以相同的方式引用它们,但一个会引发警告,一个不会。
这不是世界末日……该应用程序运行良好,但我真的很想了解为什么会发生这种情况并让我的应用程序运行干净。
这是 handleChange
:
handleChange(event) {
const attribute = event.target.name
const updatedGroup = this.state.group
updatedGroup[attribute] = event.target.value
this.setState({"group": updatedGroup})
}
原文由 skwidbreth 发布,翻译遵循 CC BY-SA 4.0 许可协议
感谢@ShubhamKhatri 和@Dekel 为我指明了正确的方向——我什至没有考虑过构造函数中设置的空字符串被有问题的值覆盖的事实。事实证明,问题的根源是在将
description
的值设置为空字符串后,我的 API 用null
覆盖了它。我通过调整我的
render
方法解决了这个问题,如下所示: