更新reducer React Redux中的嵌套状态

时间:2017-03-16 17:21:35

标签: reactjs redux state immutability reducers

我使用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"
    }
  }
}

我想更新reducer并在lastMessage之后添加一个键/值(' name':joe)。我的action.payload中有name(ex:joe)和id User(例如: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;
  }
}

1 个答案:

答案 0 :(得分:2)

利用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;
  }
}