state = {
doctor: {
name: '',
title: '',
}
}
state下有两级,第一级doctor,第二级name/title,那么我们怎样修改name的值呢
错误的做法:
this.setState({
doctor: {
name: '张三'
}
})
这样是错误的,因为this.setState
只能更改最外层属性的值,这样的结果是直接对doctor进行对象赋值,doctor下的title也被覆盖没了
正确的做法1:
let data = {name: '张三'}
let doctor = Object.assign({},this.state.doctor,data)//data合并更新state.doctorInfo至target对象
this.setState({
doctor,
})
正确做法2:
let doctor = {
...this.state.doctorInfo,
name: '张三'
}
this.setState({
doctor,
})
网友评论