如何在State中更改嵌套对象的属性?

Mak*_*sim 4 javascript object ecmascript-6 reactjs

状态看起来像这样

{
  ownRecipe: {name:""}
}
Run Code Online (Sandbox Code Playgroud)

现在我需要更改名称属性,这不起作用

this.setState({ownRecipe[name]:"Pineapple pizza"});
Run Code Online (Sandbox Code Playgroud)

这可行,但也许有更好的方法?

let ownRecipeCopy = {}
for(let key in this.state.ownRecipe){
  ownRecipeCopy[key] = this.state.ownRecipe[key];
}
ownRecipeCopy.name = e.target.value;
this.setState({ownRecipe: ownRecipeCopy});
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢大家的回答

Dup*_*cas 9

传播原始对象并更改所需的属性:

this.setState(prevState =>({
    ownRecipe : {
        ...prevState.ownRecipe,
        name : 'new name'
    }
}));
Run Code Online (Sandbox Code Playgroud)

  • 由于setState的异步特性,建议不要使用this.state获取setState中的先前状态。相反,在使用先前状态值更新状态时,始终依赖传递回调`this.setState(prevState =>({ownRecipe:...}))`。更新器功能接收到的prevState保证是最新的。更新程序的输出与prevState浅层合并。请参阅[react-setstate-usage](https://itnext.io/react-setstate-usage-and-gotchas-ac10b4e03d60)和[setState](https://reactjs.org/docs/react-component.html# setstate) (2认同)