我用了这个解决方案。
如果您有这样的嵌套状态:
this.state = {
formInputs:{
friendName:{
value:'',
isValid:false,
errorMsg:''
},
friendEmail:{
value:'',
isValid:false,
errorMsg:''
}
}
}
您可以声明handleChange函数,该函数复制当前状态并使用更改后的值重新分配它
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let statusCopy = Object.assign({}, this.state);
statusCopy.formInputs[inputName].value = inputValue;
this.setState(statusCopy);
}
这里是带有事件监听器的html。确保使用与状态对象相同的名称(在本例中为“ friendName”)
<input type=“text” onChange={this.handleChange} " name=“friendName” />
更新对象数组:
假设您有一个待办事项应用程序,并且您正在以这种形式管理数据:
this.state = {
todoItems: [
{
name: 'Learn React Basics',
status: 'pending'
}, {
name: 'Check Codebase',
status: 'pending'
}
]
}
要更新任何待办事项对象的状态,请在数组上运行一个映射并检查每个对象的某些唯一值,如果为condition=true,则返回具有更新值的新对象,否则返回相同的对象。
let key = 2;
this.setState(prevState => ({
todoItems: prevState.todoItems.map(
el => el.key === key? { ...el, status: 'done' }: el
)
}))
建议:如果对象没有唯一值,则使用数组索引。
更多请参考:
https://www.imooc.com/wenda/detail/596474