首页 > 解决方案 > 在 redux 状态的对象中添加或删除对象

问题描述

我是react-reduxreducer 的新手,这里我有一个对象作为API 调用的响应。

因此,我将其保存为jobList. 现在,我得到的响应对象是这样的:

{
   "jdId":"5c987c171251350001330f72",
   "userName":"abc",
   "location":{
      "weightage":1,
      "quickWeightage":1,
      "criteria":"abcc"
   },
   "mustHaveSkills":{
      "technologies":[
         {
            "weightage":0.5,
            "quickWeightage":1,
            "criteria":"OOPS"
         },
         {
            "weightage":0.5,
            "quickWeightage":1,
            "criteria":"OOPS"
         }
      ],
      "functionalSkills":[
         {
            "weightage":0.5,
            "quickWeightage":1,
            "criteria":"OOPS"
         },
         {
            "weightage":0.5,
            "quickWeightage":1,
            "criteria":"OOPS"
         },
         {
            "weightage":0.5,
            "quickWeightage":1,
            "criteria":"OOPS"
         },

      ]
   },
   "shouldHaveSkills":{
      "technologies":[
         {
            "weightage":0.35,
            "quickWeightage":0.7,
            "criteria":"C"
         },
         {
            "weightage":0.35,
            "quickWeightage":0.7,
            "criteria":"C"
         }
      ],
      "functionalSkills":[

      ]
   },
   "couldHaveSkills":{
      "technologies":[

      ],
      "functionalSkills":[

      ]
   },
   "goodToHaveSkills":{
      "technologies":[
         {
            "weightage":0.25,
            "quickWeightage":0.5,
            "criteria":"XAMARIN"
         }
      ],
      "functionalSkills":[

      ]
   }
}

现在,在这里我已经写了一些动作,例如,

export const add(obj, type) {   
    return {
       type: ADD_DATA,
       payload: obj
    }
}

现在,在减速器中:

 case ADD_DATE : {

// Here I want to update this object which is having a an object for the 
 //mustHaveSkills which is an key with array of objects. and I want to add that new object in this array. I also have the type as this key has two arrays in it which to be updated.
}

现在,在这里,我传递一个要更新的对象

{
  "weightage": 0.5,
  "quickWeightage": 1,
  "criteria": "OOPS"
}

type as aTechnology并且我已经为需要更新的四个键编写了单独的操作。因此,例如,我需要更新mustHaveSkills.

那么,现在我怎样才能在 reducer 状态下更新那个特定的对象呢?任何帮助都会有所帮助。谢谢。

标签: javascriptreactjsreduxreact-redux

解决方案


如果你想更新那technologies部分,mustHaveSkills你可以这样做

case ADD_DATA: 

    return {
        ...state,
        mustHaveSkills: {
            ...state.mustHaveSkills,
            technologies: [...mustHaveSkills.technologies, action.payload],
        }
    }

action.payload考虑到包含这些数据的事实

{
    "weightage": 0.5,
    "quickWeightage": 1,
    "criteria": "OOPS"
}

并且还假设state对象结构就像您发布的响应对象。


推荐阅读