如果在新状态React中缺少默认状态值,则保持默认状态值

问题描述 投票:0回答:2

我希望状态保留所有属性,即使新状态没有。是否可以轻松快捷的方式?

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 },
}
javascript reactjs state
2个回答
1
投票

定义新状态时尝试此操作

var newState= {
...this.state,
fruits:['apple','orange'],
hungry:false,
}

0
投票

这应该这样做:

this.state = { thing: ‘foo’, otherThing: 1 };
const newState = { otherThing: 5 };
this.setState(Object.assign({}, this.state, newState));

完成后状态为{thing:'foo',otherThing:5}

它将用新属性覆盖旧状态。任何在新的中都不存在的将具有旧值。

© www.soinside.com 2019 - 2024. All rights reserved.