【问题标题】:how to Modify a child object from you state in the reducer with Redux如何使用 Redux 在 reducer 中从您的状态修改子对象
【发布时间】:2019-08-06 12:39:28
【问题描述】:

我有一个包含多个对象的状态。现在我可以修改第一层的所有元素,比如 step 属性。但我想知道如何修改状态内对象的元素。

初始状态

const initialState = {
  step : 1,
  user: {
    identification : {
      email:  '',
      username: '',
    },
    localization: {
      address:  '',
      country: '',
    }}

我的payload是这个对象:

identification : {
    email: "some@html.com"
    username: "s032190" }

而我的 rootReducer 是这样的:

function rootReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_USER:
      return { ...state, user: action.payload }  
    case CHANGE_STEP:
    return { ...state, step: action.payload }  
    case ADD_FIELD: 
      Object.keys(state.altaUsuario).forEach (cat => { 
          return { ...state.user, [cat] : action.payload}          
      })
    default:
    return state
  }
};

使用循环可以吗?我尝试使用地图或 foreach,没有任何效果。 我还尝试在扩展运算符中调用属性,如下所示:

       return { ...state, altaUsuario[cat] : action.payload}     

但它给了我一个语法错误。

如有必要,我还可以修改有效负载。

有什么想法吗??

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux state


    【解决方案1】:

    你可以试试这样的

    return { ...state,user : {...state.user ,identification :action.payload }}

    【讨论】:

    • 几乎,但它在我的用户对象中创建了一个新的标识属性。现在我有user: { identification:{}, localization {}, identification{}}
    • 我的错,我弄错了对象键。谢谢你的第一个好答案!
    【解决方案2】:

    如果你的 action.payload 是

    {
      identification : {
      email: "some@html.com"
      username: "s032190"
       }
    }
    

    您必须覆盖标识属性

    return { ...state, user: { ...state.user, identification: action.payload.identification} 
    

    【讨论】:

      猜你喜欢
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 2019-02-03
      • 2016-12-24
      • 2020-04-16
      • 1970-01-01
      相关资源
      最近更新 更多