在我的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>
Run Code Online (Sandbox Code Playgroud)
但是我对此感到困惑,因为的值this.state.group.description是""在构造函数中设置的:
this.state = {
"group": {
"name": "",
"description": ""
}
}
Run Code Online (Sandbox Code Playgroud)
更令我惊讶的是,另一个输入字段引用了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>
Run Code Online (Sandbox Code Playgroud)
我在这里想念什么吗?据我所知,我已经将这两个值的初始状态设置为空字符串,并在两个输入字段中以相同的方式引用了它们,但是一个抛出警告,一个没有警告。
这不是世界末日……该应用程序运行良好,但我真的很想了解为什么会发生这种情况并使我的应用程序正常运行。
这是handleChange:
handleChange(event) {
const attribute = event.target.name
const updatedGroup = this.state.group
updatedGroup[attribute] = event.target.value
this.setState({"group": updatedGroup})
}
Run Code Online (Sandbox Code Playgroud)
如果值为 null,则通过相同的错误响应 15。所以最好输入的默认道具“值”应该是一个空字符串,以便在没有警告的情况下运行 react js 代码。
<input type="text" value={value || ''}/>;
Run Code Online (Sandbox Code Playgroud)
感谢@ShubhamKhatri和@Dekel为我指出了正确的方向-我什至没有考虑过构造函数中设置的空字符串被有问题的值覆盖的事实。事实证明,问题的根源在于将的值设置description为空字符串后,我的API被覆盖了null。
我通过调整render方法来解决此问题,如下所示:
let groupDescription;
if (!this.state.group.description) {
groupDescription = ""
} else {
groupDescription = this.state.group.description
}
return (
<label>Description<br />
<input
type="text"
name="description"
value={groupDescription}
onChange={this.handleChange}
maxLength="99" />
</label>
)
Run Code Online (Sandbox Code Playgroud)
问题出在handleChange函数上,您直接在改变状态
const updatedGroup = this.state.group
updatedGroup[attribute] = event.target.value
Run Code Online (Sandbox Code Playgroud)
用于spread operator克隆组对象
handleChange(event) {
const attribute = event.target.name
const updatedGroup = [...this.state.group]
updatedGroup[attribute] = event.target.value
this.setState({"group": updatedGroup})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7238 次 |
| 最近记录: |