简体   繁体   English

更新属性时如何避免突变状态

[英]How to avoid mutating state when updating a property

I have a function that when it is called is passed the initialState and the function to update the state (set through react hooks) 我有一个函数,当调用它时会传递initialState和用于更新状态的函数(通过react挂钩设置)

const [initialState, setInitialState] = useState("name")

const toggleValue = (initialState, setInitialState) => {
   const myVal = initialState;
   myVal["name"] = "This is a new name"
}

My expectations were that reassigning the state to a variable would not cause the state to be mutated when that variable was updated. 我的期望是,将状态重新分配给变量不会导致该变量在更新时发生突变。

However I'm noticing that when I run toggleValue initialState is changing to "This is a new name" as well as myVal. 但是,我注意到当我运行toggleValue initialState和myVal都更改为“ This is a new name”。 Is there a way to avoid mutating the state? 有没有办法避免改变状态? My goal is to update a property in the initialState object and then update the state. 我的目标是更新initialState对象中的属性,然后更新状态。

First thing is your state is not an object, it is simple string value, 首先是您的状态不是对象,而是简单的字符串值,

const [initialState, setInitialState] = useState("name")

Updating string value is very simple, 更新字符串值非常简单,

const toggleValue = (initialState, setInitialState) => { 
   setInitialState("This is a new name") //This will simply change the state
}

If your state is an object like, 如果您的状态是类似这样的对象,

const [initialState, setInitialState] = useState({name:"name"})

In that case you can change the state like, 在这种情况下,您可以更改状态,例如

const toggleValue = (initialState, setInitialState) => {  
   const myVal = {...initialState}; //This will create a copy
   myVal["name"] = "This is a new name";

   setInitialState(myVal); //This is needed to update the state.
}

Demo 演示

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

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