reactjs - 如何在 Redux 中更改对象数组中的值
问题描述
我在 Redux State 中存储了一个对象数组,每个对象内部都有一个名为 price 的键。现在,当我增加数量按钮时,我需要访问在 redux 中有键的对象并更改价格值。我能够做到这一点,但它无法正常工作,价格正在更改,但正在以 Redux 状态添加一个新对象,您可以在下面的屏幕截图中看到它。希望我能够清楚地解释这个问题。如果不是,请告诉我,以便我解释更多。
购物车组件
increment(e, item){
let qty = e.target.previousElementSibling.textContent;
qty++;
e.target.previousElementSibling.textContent = qty;
this.props.changePrice(item);
}
<div>
<input onClick={(e) =>this.decrement(e)} type="submit" value="-"/>
<span>1</span>
<input onClick={(e) => this.increment(e, item)} type="submit" value="+"/>
</div>
function mapStateToProps(state){
return({
itemlist: state.rootReducer
})
}
function mapDispatchToProps(dispatch) {
return({
removeItem: (item)=>{
dispatch({type: 'removeCart', payload: item})
},
changePrice: (item)=>{
dispatch({type: 'changePrice', payload: item})
}
})
}
export default connect(mapStateToProps, mapDispatchToProps)(Cart);
减速机组件
const changePrice = (itemArray, item)=>{
let newObject = {};
let filteredObject = itemArray.filter(reduxItem => reduxItem.id === item.id);
let newprice = filteredObject[0].price + filteredObject[0].price;
filteredObject[0].price = newprice;
newObject = filteredObject;
const something = ([...itemArray, newObject]);
return something;
}
const reducer = (state = [], action) =>{
switch (action.type) {
case 'Add':
return [...state, action.payload]
case 'removeCart':
const targetItemIndex = state.indexOf(action.payload);
return state.filter((item, index) => index !== targetItemIndex)
case 'changePrice':
return changePrice(state, action.payload)
default:
return state;
}
}
export default reducer;
解决方案
filteredObject
是一个数组。您在此语句中将 覆盖newObject
为一个数组 newObject = filteredObject
。所以 thenewObject
是一个数组( in [...itemArray, newObject]
)而不是一个对象。保持简单而没有不必要的复杂性。您可以使用Array.map
. 所以改为这样做
const changePrice = (itemArray, item) => {
return itemArray.map(reduxItem => {
if(reduxItem.id === item.id){
reduxItem.price = reduxItem.price + reduxItem.price
}
return reduxItem
});
};
有关更多信息,请参阅此内容https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#inserting-and-removing-items-in-arrays
希望这可以帮助!
推荐阅读
- html - iframe 的大小未在嵌入式仪表板上动态调整
- aws-codebuild - AWS Sam package 命令在构建规范期间失败
- sql - 声明 Varchar - Teradata
- django - ModuleNotFoundError:没有名为“webpushapi”的模块
- python - 有人可以告诉我如何在 python 中读取该文件吗?
- javascript - 错误:连接 ENOENT /Applications/MAMP/tmp/mysql/mysql.sock
- html - 为什么 chrome 从下拉项中删除引导程序的 .active 类?
- solidity - 在特定地址使用合约
- c# - Blazor 中的最佳实践是什么:将大量业务逻辑放入 *.razor 文件或控制器中?
- node.js - 如何在猫鼬中设置外键?