我有一个处于这种状态的组件:
state = {
data: {
name: ...,
place: ...,
responsible: {
name: ...,
mail: ....
}
}
}
我有一个组件字段,该字段的onChange会随着事件更新状态:
handleOnSave = (id, data) => {
if (this.state[id] !== data) {
const newData = {
...this.state.data,
[id]: data,
};
this.setState({data: newData})
}
}
如果我想更改状态数据内的负责对象,该怎么办?我的意思是,通过此功能,我可以更改state = {place:'newPlace'},我需要更改一个对象:负责任
答案 0 :(得分:0)
您要合并值。使用setState
的回调重载版本
this.setState((state, props) => ({
data: {
...state.data,
responsible: data.data.responsible
}
});
答案 1 :(得分:0)
您可以调用handleOnSave
传递一个对象,例如:
handleOnSave({name: 'name'})
或handleOnSave({responsible: {name: 'name'}})
handleOnSave = ({responsible, ...rest}) => {
const newData = {
...this.state.data, ...rest,
responsible: {
...this.state.data.responsible, ...responsible
}
};
this.setState({data: newData});
}