首页 > 解决方案 > 如何在 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;

标签: reactjsreduxreact-reduxstate

解决方案


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

希望这可以帮助!


推荐阅读