通过 Redux 将对象添加到具有对象数组的状态

Add a Object into state with array of Object by Redux

当我的后端发送一个带有值的负载时:

Object {
  "__v": 0,
  "_id": "621ef5eec33b5c6d9d184563",
  "category": "621ef5e8c33b5c6d9d18455e",
  "createdAt": "2022-03-02T04:43:26.834Z",
  "description": "",
  "name": "Hair and Nails",
  "price": 50,
  "updatedAt": "2022-03-02T04:43:26.834Z",
},

如何将此对象添加到我的 serviceReducer const 初始状态 = { 正在加载:假的, 错误:错误, 服务类别:[],//! serviceCategories 是一个数组 }; 首先,我映射 serviceCategories 并选择我需要的 serviceCategories

        return {
            ...state,
            serviceCategories: state.serviceCategories.map((serviceCateogory) => {
                return serviceCateogory._id === action.payload.category 
                ? serviceCateogory //! here How I to add that object to services of serviceCateogory
                : serviceCateogory;
            }),
            // ),
        };

这是 serviceCategories 的结构:

[
 Object {
  "__v": 0,
  "_id": "621ef5e8c33b5c6d9d18455e",
  "createdAt": "2022-03-02T04:43:20.754Z",
  "name": "Category1",
  "services": Array [
    Object {
      "__v": 0,
      "_id": "621ef5eec33b5c6d9d184563",
      "category": "621ef5e8c33b5c6d9d18455e",
      "createdAt": "2022-03-02T04:43:26.834Z",
      "description": "",
      "name": "Service1",
      "price": 50,
      "updatedAt": "2022-03-02T04:43:26.834Z",
    },
    Object {
      "__v": 0,
      "_id": "621ef7d1c33b5c6d9d1845b1",
      "category": "621ef5e8c33b5c6d9d18455e",
      "createdAt": "2022-03-02T04:51:29.262Z",
      "description": "",
      "name": "Service2",
      "price": 50,
      "updatedAt": "2022-03-02T04:51:29.262Z",
    },
  ],
  "updatedAt": "2022-03-02T05:08:35.520Z",
},
 Object {
  "__v": 0,
  "_id": "621ef5e8c33b5c6d9d18455e",
  "createdAt": "2022-03-02T04:43:20.754Z",
  "name": "Category2",
....
]

你需要先从redux state中找到具体类别的索引,然后将服务附加到其中。 喜欢:

let categories=[...state.serviceCategories];     
let catIndex=categories.findIndex((item)=>item._id===action.payload.category);
if(catIndex!=-1) categories[catIndex].services.push(object); // append object (service) as you wish.
state.serviceCategories=categories;