我希望状态保留所有属性,即使新状态没有。是否可以轻松快捷的方式?
this.state={
fruits:['apple','orange'],
hungry:false,
drinks:{ alchohol:false, diary:false }
}
var newState= {
fruits:['apple','orange'],
hungry:false,
}
// new state
this.setState({...newState});
i get state
{
fruits:['apple','orange'],
hungry:false,
}
but i want
{
fruits:['apple','orange'],
hungry:false,
drinks:{ alchohol:false, diary:false },
}
定义新状态时尝试此操作
var newState= {
...this.state,
fruits:['apple','orange'],
hungry:false,
}
这应该这样做:
this.state = { thing: ‘foo’, otherThing: 1 };
const newState = { otherThing: 5 };
this.setState(Object.assign({}, this.state, newState));
完成后状态为{thing:'foo',otherThing:5}
它将用新属性覆盖旧状态。任何在新的中都不存在的将具有旧值。