gpt4 book ai didi

reactjs - 类型错误 : Cannot assign to read only property 'quantity' of object '#'
转载 作者:行者123 更新时间:2023-12-04 17:13:16 29 4
gpt4 key购买 nike

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

类型错误:无法分配给对象“#”的只读属性“数量”

我如何才能改变这种状态。

求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救
求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救求救

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,
});
}

关于reactjs - 类型错误 : Cannot assign to read only property 'quantity' of object '#<Object>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69095445/

29 4 0