[英]Attempted to assign to readonly property
first of all i get my redux array then in my_function copy that into new variable like below:首先,我得到我的 redux 数组,然后在 my_function 中将其复制到新变量中,如下所示:
let transactions_list = useSelector(state => state.transactions_list.value);
let new_transactions_list = [...transactions_list];
when i want to change my new_transactions_list very deeply i got the error当我想非常深入地更改我的 new_transactions_list 时,我得到了错误
const my_function = () => {
let new_transactions_list = [...transactions_list];
new_transactions_list[yearIndex].data_yearly[monthIndex].data_monthly.push(new_obj);
}
but when i define an array in class(without redux), it's work但是当我在类中定义一个数组时(没有 redux),它的工作
Even if you are using the spreading [...transactions_list]
, you are still only copying the first level of the array, which means that the object below that array is still the same one that redux uses.即使您使用扩展
[...transactions_list]
,您仍然只是复制数组的第一层,这意味着该数组下面的对象仍然是 redux 使用的对象。
You have 2 options:您有 2 个选择:
This is how redux recommends you to update nested object link这就是 redux 推荐你更新嵌套对象链接的方式
function updateVeryNestedField(state, action) {
return {
...state,
first: {
...state.first,
second: {
...state.first.second,
[action.someId]: {
...state.first.second[action.someId],
fourth: action.someValue
}
}
}
}
}
Or you can use something like immer , which will allow you to update your object even with immutable like this或者你可以使用像immer这样的东西,它允许你更新你的对象,即使像这样不可变
const nextState = produce(baseState, draft => {
draft[1].done = true
draft.push({title: "Tweet about it"})
})
Either way, you will have to update your redux state afterward since this change will only be local in your code and not the global redux.无论哪种方式,您之后都必须更新您的 redux 状态,因为此更改仅在您的代码中是本地的,而不是全局 redux。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.