更新对象数组中的属性 [英] Update a property in an array of objects

查看:47
本文介绍了更新对象数组中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用React在对象数组中增加数量属性.但是我不知道如何才能更新该项目.

I try to increment a quantity property in an array of objects with React. But I can't figure out how I can reach the item to update.

我尝试过的事情:

const initialState = {
  items: [{
      id: 254,
      quantity: 1
    },
    {
      id: 493,
      quantity: 1
    }
  ],
};

const payload = {
  id: 254
};

function updateProduct(state, action) {
  return state.items.map((item, i) => {
    if (item.id === action.id) {
      return {
        ...state,
        items: [
          ...state.items,
          {
            [i]: {
              quantity: state.items[i].quantity + 1
            }
          }
        ]
      };
    }
  });
}

返回的对象应该是:

{
  items: [{
      id: 254,
      quantity: 2
    },
    {
      id: 493,
      quantity: 1
    }
  ],
}

感谢您的帮助!

推荐答案

我将建议一些更改:

  1. 将操作约定与{type,payload}一起使用
  2. 在减速器中执行操作.

因此产生:

const reducer = (state, action) => {
  const {type, payload} = action;

  switch(type) {
    case 'update_quantity':
      const {id: itemId, quantity} = payload
      return ({
        ...state,
        items: state.items.map(item => (item.id === itemId ? {...item, quantity} : item)
    default:
      return state;
  }
}

然后更新:

dispatch({type:'update_quantity',有效负载:{id:'xxx',数量:3}});

这篇关于更新对象数组中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆