[英]Update state using function .map() is mutated state?
I'm still new to react and I still don't really understand about mutated the state. 我仍然是新来的反应者,我仍然对变态还不太了解。
I have seen many posts about this but I do not understand how the mutation process happened so I think it is necessary to ask this. 我已经看到很多关于此的帖子,但是我不了解突变过程是如何发生的,因此我认为有必要提出这一问题。
First i need to know is this called mutated state? 首先,我需要知道这称为突变状态吗?
this.setState(prevState=>({
colors:this.state.colors.map((c,i)=>{
return{
original_color:c.original_color,
hex_color:c.hex_color,
isActive:false
}
})
}))
OR 要么
let newData = this.state.colors.map((c,i)=>{
return{
original_color:c.original_color,
hex_color:c.hex_color,
isActive:false
}
})
this.setState({
colors: newData
})
in this case i just want to set all of this value isActive
to false
在这种情况下,我只想将所有此值
isActive
为false
Last 持续
i want to set this value to empty 我想将此值设置为空
this.setState({
colors:[]
})
Your state is not mutated in any case. 您的状态在任何情况下都不会改变。
.map()
returns a new array. .map()
返回一个新数组。 Your state is only mutated when you directly assign it to another value without calling .setState()
like so: 仅当您将状态直接分配给另一个值而不调用
.setState()
时,状态才会发生变化,如下所示:
this.state.value = anotherValue;
Or: 要么:
this.state.value.push(anotherValue)
Since .map()
returns a new array as a result, using it is safe and is not considered a mutation. 由于
.map()
作为结果返回一个新数组,因此使用它是安全的,不被视为突变。
Basically, anything that doesn't change the original state or any direct references to it, is not considered a mutation. 基本上,任何不更改原始状态或直接引用原始状态的内容都不会被视为突变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.