简体   繁体   English

reactjs更改状态对象内的对象属性

[英]reactjs changing object attributes inside the state object

I get an object as response from a get. 我从get得到一个对象作为响应。

Now I assign the object to a state var (object) like this: 现在,我将对象分配给状态var(对象),如下所示:

 this.setState({editData: response.data})

Is there a way to change the values within this object? 有没有办法更改此对象内的值?

I thought about something like this: 我想到了这样的事情:

this.setState({editData.[var]: [value]})

thanks 谢谢

Firstly you have to remember that you should never mutate state object directly. 首先,您必须记住,永远不要直接改变状态对象。 So first you shold make a copy of state object and mutate the copy. 因此,首先您要制作一个状态对象的副本并对该副本进行突变。 Then set this copy as state. 然后将此副本设置为状态。 You can use spread syntax to achieve it: 您可以使用传播语法来实现它:

this.setState((prevState) => ({editData: {...prevState.editData, [var]: value}}));

Here is working example showing that source object is not mutated: 这是一个工作示例,显示源对象未发生突变:

 let state = { editData: { age: 22 } }; let age = "age"; let stateCopy = {editData: {...state.editData, [age]: 100}}; console.log(state); console.log(stateCopy); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM