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

时间:2019-09-18 00:44:02

标签: javascript reactjs

我有一个函数,当调用它时会传递initialState和用于更新状态的函数(通过react钩子设置)

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

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

我的期望是,将状态重新分配给变量不会导致状态在该变量更新时发生突变。

但是我注意到当我运行toggleValue时,initialState和myVal都更改为“ This is a new name”。有没有办法避免改变状态?我的目标是更新initialState对象中的属性,然后更新状态。

1 个答案:

答案 0 :(得分:1)

第一件事是您的状态不是对象,它是简单的字符串值,

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

更新字符串值非常简单,

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

如果您的状态是类似的对象,

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

在这种情况下,您可以更改状态,

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