【发布时间】:2019-09-12 00:45:00
【问题描述】:
所以我基本上开始学习 Redux 并想创建一个简单的商店应用程序,您可以在其中将手机添加到购物车中。我创建了一个状态对象,并在其中创建了一个包含对象的数组,其中包含商店中的项目列表。我想更新 [+] 点击订购的商品数量,但它现在不起作用。我已经为此苦苦挣扎了 1 个小时,但仍然看不出问题出在哪里。
Reducer 长这样:
const initialState = {
liked:0,
cart:0,
item: [
{
id:1,
name: 'Iphone 8',
price: 2000,
desc: 'The new Iphone 8 available at our store!',
orderedNum: 0
},
{
id:2,
name: 'Iphone 6',
price: 1500,
desc: 'The new Iphone 6 available at our store!',
orderedNum: 0
},
{
id:3,
name: 'Samsung S8',
price: 2200,
desc: 'The new Samsung S8 available at our store!',
orderedNum: 0
},
{
id:4,
name: 'Xiaomi Mi 6',
price: 1400,
desc: 'The new Xiaomi Mi 6 available at our store!',
orderedNum: 0
},
{
id:5,
name: 'Pocophone P1',
price: 2100,
desc: 'The new Pocophone P1 available at our store!',
orderedNum: 0
},
{
id:6,
name: 'Nokia 3310',
price: 999,
desc: 'The new Nokia 3310 available at our store!',
orderedNum: 0
},
]
}
const reducer = (state = initialState, action) => {
const newState = {...state};
switch(action.type) {
case 'ADD_NUM':
return state.item.map((el, index) => {
if(el.id === action.id ){
return {
...el,
orderedNum: el.orderedNum + 1
}
}
return el;
})
default:
break;
}
return newState;
}
export default reducer;
-
我有行动:
const mapStateToProps = state => { return { item: state.item } } const mapDispatchToProps = dispatch => { return { addNum: () => dispatch ({ type: 'ADD_NUM', id: this.props.id, value: 1 }) }
我以不同的方式尝试过,但我认为这可能是在减速器中嵌套的问题。
有人可以建议吗?
【问题讨论】:
-
您的减速器看起来不正确,您当前正在返回一个基于映射的
state.item的新数组,但不是具有属性item的对象,它是一个数组...你有没有已经调试了您从组件内部的mapStateToProps返回的内容,或者到目前为止您是如何调试问题的?
标签: arrays reactjs redux state store