[英]How to avoid mutating state when updating a property
我有一個函數,當調用它時會傳遞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對象中的屬性,然后更新狀態。
首先是您的狀態不是對象,而是簡單的字符串值,
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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.