Getting a ID back from a reducer in redux

纵饮孤独 提交于 2019-12-05 09:39:27
just-boris

I think that you should dispatch only one action here: addBookmark(), which accepts both bookmark object and folder.

Your code, which handles adding bookmark object into folder should be part of reducer.

Also, refer the Todos example in Redux project. It has id provided in action creation to make it possible to read it in the component. You can also use current state to compute latest id:

function addBookmark(bookmark, folder) {
   return (dispatch, getState) => {
       const newBookmark = Object.assign({
         id: Math.max(0, ...getState().bookmarks.map(b => b.id)) + 1,
       }, bookmark);
       dispatch({
         type: 'ADD_BOOKMARK',
         bookmark: newBookmark,
         folder: folder
       });
   }
}

Notice that example requires redux-thunk middleware to dispatch those actions.

Then you can get access to bookmark with id in the folders reducer

function folderReducer(state = [], action) {
  if(action.type === 'ADD_BOOKMARK') {
     return state.map(folder => {
       if(folder === action.folder) {
         return Object.assign({}, folder, {children: [...folder.children, action.bookmark.id]}
       }
       return folder;
     })
  }
  //another reducer code
  return state;
} 

Reducers are just manipulating your store's instance. You may the current snapshot of your state using getState()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!