不使用Immutability Helper

时间:2017-08-29 05:50:54

标签: reactjs redux react-redux

我有一个状态Object,如下所示:

//State Object
playlistDict: {
  someId1: {
    active: false,
    id: 'someId',
    name: 'someName',
    pages: [ 'pageId1', 'pageId2', 'pageId3', etc ]  // I want to remove an element from this array
  },
  someId2: {
    active: false,
    id: 'someId2',
    name: 'someName2',
    pages: [ 'pageId11', 'pageId22', 'pageId33', etc ] // I want to remove an element from this array
  }
}

我尝试编写一个删除页面元素的reducer,指定删除而不使用immutability helper

这就是我尝试做的事情,但我的语法已关闭,而且我不确定编写减速器的正确方法是什么:

export function _removePageFromPlaylist( playlistId, pageIndex ) {
  return { type: types.REMOVE_PAGE_FROM_PLAYLIST, playlistId, pageIndex };
}

case types.REMOVE_PAGE_FROM_PLAYLIST: {    
      let playlistCopy = Object.assign( {}, state.playlistDict[ action.playlistId ]);
      playlistCopy.pages = Object.assign( {}, state.playlistDict[ action.playlistId ].pages );
      playlistCopy.pages.splice( action.pageIndex, 1 );

      return Object.assign({}, state, {
        playlistDict: { ...state.playlistDict, playlistDict[ action.playlistId ]: playlistCopy }  // doesn't like this syntax in particular
      });
    }
编辑:关于人们认为它与我的其他问题相同,我提出这个问题是因为我试图弄清楚我的减速器使用不变性助手是否搞砸了我的问题Firebase数据库,所以我试图找出如何编写reducer而不使用immutability helper,这样我就可以帮助消除我的bug。

2 个答案:

答案 0 :(得分:1)

使用spread operator,并按如下方式编写:

case types.REMOVE_PAGE_FROM_PLAYLIST: {    
    let playlistCopy = [...(state.playlistDict[ action.playlistId ].pages)];
    playlistCopy.splice( action.pageIndex, 1 );

    return {
        ...state,
        playlistDict: {
            ...state.playlistDict,
            [action.playlistId]: {
                ...state.playlistDict[action.playlistId],
                pages: playlistCopy
            }
        }
    }
}

答案 1 :(得分:1)

使用对象传播运算符:

case types.REMOVE_PAGE_FROM_PLAYLIST: {
  return {
    ...state,
    playlistDict: {
      ...state.playlistDict,
      [action.playlistId]: {
        ...state.playlistDict[action.playlistId],
        pages: [...state.playlistDict[action.playlistId].pages].splice(action.pageIndex, 1)
      }
    }
  }
}