将对象推送到数组数组-react-redux

时间:2020-09-17 12:06:38

标签: reactjs redux react-redux

我正在尝试在特定商店中的商品数组中添加新对象,但是redux不会重新渲染。我已经尝试了spread and concat方法,因为不推荐使用push函数,但是它不起作用。

const initialState ={
  stores: []
}

//提取数据后的存储如下:

stores: [
  {
    name: "iPhone store", 
    id: 12345, 
    items: [
      {id: 1233, name: "iPhone 7"}
    ]
  }
]

我想在特定商店中添加新商品,而reducer看起来像这样:

const store_new_item = (state, action) => {
  // not re-rendering
  let stores = [...state.stores];
  const index = stores.findIndex((a) => a._id === action.storeid);

  stores[index] = {
    ...stores[index],
    items: stores[index].items.concat({ ...action.item, _id: nanoid() }),
  };

  return {
    ...state,
    loading: false,
    stores: stores,
  };
};

感谢您的反馈!

1 个答案:

答案 0 :(得分:0)

stores[index] = {
    ...stores[index],
    items: [...stores[index].items, action.item],
  };