gpt4 book ai didi

javascript - 如果新状态 React 中缺少默认状态值,则保留默认状态值

转载 作者:行者123 更新时间:2023-12-03 02:45:46 25 4
gpt4 key购买 nike

我希望该状态保留所有属性,即使新状态没有某些属性。是否可以通过简单快捷的方式实现?

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,
}

关于javascript - 如果新状态 React 中缺少默认状态值,则保留默认状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48100601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com