在 reducer React Redux 中更新嵌套状态

Update a nested state in a reducer React Redux

我正在使用 redux 和 reactjs。这是我的减速器状态:

{
 XSAUZHNAKZJ : //id User
  {
   AZRAERAZEAZ : //id Conversation - always one object 
    {
     timestamp : 123123123,
     lastMessage : "hello"
    }
  },
 BLZEJARNAELKR : //id User
  {
   AANALZKJAZ : //id Conversation - always one object
    {
     timestamp : 123123123,
     lastMessage : "hello"
    }
  }
}

我想更新减速器并在 lastMessage 之后添加一个 key/value ('name' : joe)。我的 action.payload 中有名称值(例如:joe)和用户 ID(例如:XSAUZHNAKZJ)。这是我的代码,但似乎我做的不对。

export default function(state={},action){
  switch(action.type){
    case 'GET_USER_INFO':
      var tempState = Object.assign({}, state);
      var conversation = tempState[action.payload.key];
      var conversationDetail = conversation[Object.keys(conversation)[0]];
      conversationDetail['name']=action.payload.val().name;
      return tempState;
    default:
      return state;
  }
}

利用immutability helper将新对象赋值给嵌套状态

import update from 'immutability-helper';

export default function(state={},action){
  switch(action.type){
    case 'GET_USER_INFO':
         return update(state, {
             [action.payload.key]: {
                   [Object.keys(state[action.payload.key])[0]]: {
                          $merge: {name: action.payload.name}
                   }
             }
         })
    default:
      return state;
  }
}