TypeError: Cannot assign to read only property 'quantity' of object '#<Object>'

TypeError: Cannot assign to read only property 'quantity' of object '#<Object>'

我正在尝试修改数组orderedList 中obj meal 的字段quantity。 这是错误:


TypeError: 无法分配给对象“#”的只读 属性 'quantity'


我怎样才能改变这种状态。


请help.Pleasehelp.Pleasehelp.Pleasehelp.Pleasehelp.Pleasehelp.Please帮忙。 请help.Pleasehelp.Pleasehelp.Pleasehelp.Pleasehelp.Pleasehelp.Please帮忙


import {createSlice} from "@reduxjs/toolkit";

const menuList = [
    {
        id: 'm1',
        name: 'Sushi',
        description: 'Finest fish and veggies',
        price: 22.99,
        quantity: 0
    },
    {
        id: 'm2',
        name: 'Schnitzel',
        description: 'A german specialty!',
        price: 16.5,
        quantity: 0
    },
    {
        id: 'm3',
        name: 'Barbecue Burger',
        description: 'American, raw, meaty',
        price: 12.99,
        quantity: 0
    },
    {
        id: 'm4',
        name: 'Green Bowl',
        description: 'Healthy...and green...',
        price: 18.99,
        quantity: 0
    },
];

const initialStateMeals = {
    menuList,
    orderedList: [],
    numberOfOrderedMeals: 0,
    showCart: false,
    totalAmount: 0
}

const counterSlice = createSlice({
    name: 'meals',
    initialState: initialStateMeals,
    reducers: {
        add(state, action) {
            state.numberOfOrderedMeals += +action.payload.input;
            let totalAmountTemp = state.totalAmount + action.payload.meal.price * action.payload.input;
            state.totalAmount = +totalAmountTemp.toFixed(2);

            let mealIsInList = state.orderedList.filter(meal => meal.id === action.payload.meal.id).length > 0;

            if (!mealIsInList) {
                state.orderedList.push(action.payload.meal);
                state.orderedList.filter(meal => meal.id === action.payload.meal.id)[0].quantity = 1;
                //on this line I have this error
                //TypeError: Cannot assign to read only property 'quantity' of object '#<Object>'
            } else {
            }
        },
        remove(state, action) {
            state.numberOfOrderedMeals -= +action.payload.input;
        }
        ,
        closeCart(state) {
            state.showCart = false;
        }
        ,
        showCart(state) {
            state.showCart = true;
        }
    }
});

export default counterSlice.reducer;
export const mealsAction = counterSlice.actions;

我的猜测是 redux-toolkit 正在保护您免于改变操作的 payload 对象,因为这种改变可能会泄漏到任何其他侦听相同操作的 reducer 中。

不是推入数组,然后再次迭代它只是为了找到你推入的元素,这将是数组中的最后一个元素,顺便说一句,你可以只创建一个具有所需属性的新对象,并将其推入数组。

if (!mealIsInList) {
  state.orderedList.push({
    ...action.payload.meal,
    quantity: 1,
  });
}