【发布时间】:2020-07-02 07:30:49
【问题描述】:
我正在尝试在paymentMethods 数组内的banking_cards array 中添加一张新卡。 banking_cards 数组位于 paymentMethods 数组内。所以我想在banking_cards 数组中插入新的卡片对象。我下面的代码产生了一个错误,上面写着state.paymentMethods.banking_cards is not iterable。
注意
banking_cards 数组在paymentMethods 数组内
export const initialState = {
paymentMethods: [],
};
case paymentMethodConstants.ADD_CARD_SUCCESS:
return {
...state,
paymentMethods: [
...state.paymentMethods,
banking_cards: [...state.paymentMethods.banking_cards, action.payload],
],
};
JSON
paymentMethods = [
{
"id": 8,
"customer_token": "epofjoe",
"banking_cards": [
{
"id": 1,
"banking_token": "AAA",
"last_4": "0006",
"exp_year": 2021,
"exp_month": 12,
"cvc": 876
},
{
"id": 2,
"banking_token": "BBB",
"last_4": "0002",
"exp_year": 2022,
"exp_month": 12,
"cvc": 877
},
]
}
]
【问题讨论】:
-
在
initialState中,paymentMethods是一个数组,但在你的reducer 函数中,它是一个对象?因为你有paymentMethods: {... -
@tanmay。
paymentMethods应该是一个数组。paymentMethods包含banking_cards,它也是一个数组。我需要在banking_cards中添加新的卡片对象 -
javascript 中的数组不能包含字符串键...所以
banking_cards没有任何意义。添加你想要实现的结构。 -
@StackedQ。请参阅已编辑的问题。如您所见,
banking_cards是paymentMethods数组中的一个数组。当我想添加一张新卡时,它应该插入到banking_cards那里。 -
@YevgenGorbunkov。你能重写我的代码吗?谢谢
标签: javascript reactjs redux ecmascript-6 react-redux