简体   繁体   English

如何在Redux + React中更新嵌套对象属性?

[英]How to update nested object property in Redux + React?

So first, the user object with a few properties ( name , color , age ) gets set up via SET_USER , and I would like to update the name property inside the user object via UPDATE_USER_NAME , yet when I do it with the following code down below with the nested looped in UPDATE_USER_NAME , the name property doesn't get updated. 所以第一, user有一些属性(对象namecolorage )获取通过建立SET_USER ,我想更新的name里面属性user通过对象UPDATE_USER_NAME ,但是当我用下面的代码做楼下嵌套循环在UPDATE_USER_NAMEname属性不会更新。

What am I doing wrong? 我究竟做错了什么? If I do something like user: {action.name, ...state.user} , the object user gets updated and works, but that just creates another new property from action.name rather than updating the current name inside the user object. 如果我做类似user: {action.name, ...state.user} ,则对象user将得到更新并可以工作,但这只是从action.name创建另一个新属性,而不是更新user对象内的当前name

const DEFAULT_STATE = {
  user: {},
}

export default function(state = DEFAULT_STATE, action) {\
  switch(action.type) {
    case actionTypes.SET_USER:
      return {
        ...state,
        user: action.user,
      }

    case actionTypes.UPDATE_USER_NAME:
      return {
        ...state,
        user: {
          name: action.name,
          ...state.user,
        }
      }

    default:
      return state
  }
}

You just need to change the order of the spread a bit: 您只需要稍微改变点差的顺序即可:

case actionTypes.UPDATE_USER_NAME:
      return {
        ...state,
        user: {
          ...state.user,
          name: action.name,
        }
      }

This will set user to the current state.user and then override name . 这会将user设置为当前state.user ,然后覆盖name the spread works like Object.assign (from left to right). 传播类似于Object.assign (从左到右)。 This is because assigning the same keys in an object literal will be "last one wins". 这是因为在对象文字中分配相同的键将是“最后一个获胜”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM