【发布时间】:2025-12-11 13:00:01
【问题描述】:
我正在尝试在数组中传播所有值并在我的减速器中附加一个新对象。
我的状态界面:
export interface IBasketState {
products: [
{
id: number | undefined;
name: string;
smallQ: number; //small packages quantity
smallTotalP: number; //price for all small packages
largeQ: number; //large packages quantity
largeTotalP: number; //price for all large packages
orderPrice: number; //total price of this order
}
];
totalPrice: number;
}
Reducer添加item功能:
const BasketReducer = (basketState: IBasketState, action: IBasketAction): IBasketState => {
//ADD ITEM
if (action.type === "Add item") {
const { id, name, smallQ, smallP, largeQ, price } = action.payload;
let smallTotalPrice = smallQ * smallP; //total price for small packages
let largeTotalPrice = largeQ * price; //total price for large packages
const orderPrice = smallTotalPrice + largeTotalPrice; //total price of this order
return {
products: [
...basketState.products, //--> **THIS IS NOT WORKING**
{
id: id,
name: name,
smallQ: smallQ,
smallTotalP: smallTotalPrice,
largeQ: largeQ,
largeTotalP: largeTotalPrice,
orderPrice: orderPrice,
},
],
totalPrice: basketState.totalPrice + orderPrice,
};
}
//Default action
return basketState;
};
当我将鼠标悬停在 ...basketState.products 上时,我收到一条错误消息:
输入 '[{ id: number |不明确的;名称:字符串;小Q:数字; smallTotalP:数字;大Q:数字; largeTotalP:数字;订单价格:数量; }, { id: 数字 |不明确的;名称:字符串;小Q:数字; smallTotalP:数字;大Q:数字; largeTotalP:数字;订单价格:数量; }]' 不能分配给类型 '[{ id: number |不明确的;名称:字符串;小Q:数字; smallTotalP:数字;大Q:数字; largeTotalP:数字;订单价格:数量; }]'。
来源有 2 个元素,但目标只允许 1.ts(2322)
BasketContext.tsx(8, 2):预期的类型来自属性“products”,在此处声明的类型为“IBasketState”
问题是在我的界面中我只在 products 数组中声明了一个对象而我现在尝试拥有 2 个吗?如果是这样,我该如何绕过它?
【问题讨论】:
-
这对*.com/questions/64308563/…有帮助吗?
标签: javascript reactjs typescript ecmascript-6