【发布时间】:2020-10-15 14:30:07
【问题描述】:
您好,我刚开始使用 react native 开始 redux,我正在尝试制作一个送餐应用程序。例如,每种食物都有饮料或甜点等选项。我希望如果用户添加一个购物篮和一个项目,我们会检查选择的选项是否相同以增加数量,如果它们不同,我想将另一个具有新选项的项目添加到全局状态。只有我尝试了很多东西,似乎都没有达到我的期望。我传递给全局状态的数据结构就是这种形式。
cartProduct = [
{
id: itemId,
restaurantName: restaurantName,
name: itemName,
quantity: quantity,
price: price
selectedOption: [
optionId: optionId,
itemId: itemId,
name: itemName,
]
}
]
这是我在减速器中使用添加到购物车操作编写的代码
switch (action.type) {
case 'ADD_TO_CART':
const cartProductIndex = state.cartProduct.findIndex(item => item.id === action.value.id)
if (cartProductIndex == -1) {
nextState = {
...state,
cartProduct: [...state.cartProduct, action.value]
}
} else {
state.cartProduct[cartProductIndex].selectedOption.map(item => {
if (item.item === action.value.selectedOption.item) {
let newArray = [...state.cartProduct]
newArray[cartProductIndex] = {
...newArray[cartProductIndex],
quantity: state.cartProduct[cartProductIndex].quantity + 1,
totalPrice: state.cartProduct[cartProductIndex].totalPrice + action.value.totalPrice
}
nextState = {
...state,
cartProduct: newArray
}
} else {
nextState = {
...state,
cartProduct: [...state.cartProduct, action.value]
}
}
})
}
return nextState || state
【问题讨论】:
-
对于第一篇文章,感谢您展示所有代码。我会在下面告诉你我会做什么。
标签: javascript reactjs react-native redux react-redux