[英]State Mutation detected when updating Redux Values
所以我對 React-Redux 還很陌生,我遇到了這個問題,如果我在 redux 中用新的 object 更新這個數組,我會收到以下錯誤
Uncaught Invariant Violation: A state mutation was detected between dispatches, in the path `settingsObject.arrayForSettings.0.updatedObject`. This may cause incorrect behavior.
僅當我使用新值更新 redux 中的 state 時才會出現問題,在以前的值上沒有錯誤。 給我錯誤的代碼如下。
let tempArrayForSettings = [...props.arrayForSettings];
tempArrayForSettings.forEach((element:any) => {
if(element.settingsType === "DesiredSettingType")
{
//modify elements of a JSON object and add it to the element
element.updatedObject = JSONUpdatedObject;
}
//call the action method to update the redux state
updateAction(tempArrayForSettings);
});
錯誤將我指向以下鏈接: Redux 錯誤
我知道我沒有更新 object 我是從道具中獲取的,而是使用擴展運算符制作副本,所以我真的不知道為什么每當我觸發 updateAction function 時都會出現錯誤。
好吧,你的 line element.updatedObject = JSONUpdatedObject;
正在修改Redux 商店中的 object 。 element
是對您的商店 object 的直接引用。 你需要在這里做一個不可變的副本 - 你上面的傳播只做一個淺拷貝,但這里的項目仍然是相同的。
一般來說,你不應該在你的組件中,而是在你的 Reducer 中做這樣的邏輯。 (請參閱有關此主題的樣式指南)這還為您提供了無需關心不變性的好處,因為在createSlice
reducers 中您可以簡單地修改數據。
您正在更新數組內的 object,因此您在上面創建的擴展運算符僅克隆數組本身,而不是數組內的對象。 在 Javascript 中,對象通過引用傳遞( 在此處閱讀更多內容)
要修復此警告,您需要復制 object 本身,為此,您需要在數組中找到要更改的特定 object。
嘗試這個:
const { arrayForSettings } = props;
const modifiedSettings = arrayForSettings.map((element:any) => {
if(element.settingsType === "DesiredSettingType")
{
//modify elements of a JSON object and add it to the element
return {
...element,
updatedObject: JSONUpdatedObject,
}
}
return element;
}
updateAction(modifiedSettings);
});
此外,建議此邏輯存在於 reducer 端,而不是您的組件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.