admin管理员组

文章数量:1302269

I'm learning Redux and having trouble trying to figure out how to add a key pair to a dictionary:

//Page Dictionary    
{
  randomId1: { aPageObj },
  randomId2: { aPageObj }, etc
}

I tried this but that doesn't work

//action
export function addPage( pageId, pageObj ) {
  return { type: types.ADD_PAGE, pageId, pageObj };
}

//reducer
case types.ADD_PAGE: {
  return Object.assign({}, state, {
    pages: {
      ...state.pages, action.pageId: action.pageObj
    }
  });
}

What am I doing wrong? Still trying to figure out how to not mutate the state..

I'm learning Redux and having trouble trying to figure out how to add a key pair to a dictionary:

//Page Dictionary    
{
  randomId1: { aPageObj },
  randomId2: { aPageObj }, etc
}

I tried this but that doesn't work

//action
export function addPage( pageId, pageObj ) {
  return { type: types.ADD_PAGE, pageId, pageObj };
}

//reducer
case types.ADD_PAGE: {
  return Object.assign({}, state, {
    pages: {
      ...state.pages, action.pageId: action.pageObj
    }
  });
}

What am I doing wrong? Still trying to figure out how to not mutate the state..

Share Improve this question asked Aug 11, 2017 at 20:41 user1189352user1189352 3,88513 gold badges59 silver badges99 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

You need to use puted property name of object literal (with []):

pages: {
  ...state.pages, [action.pageId]: action.pageObj
}

Furthermore if you can use object spreas syntax, you can omit Object.assign, for example:

return {
  ...state,
  pages: {
    ...state.pages, [action.pageId]: action.pageObj
  }
}

Although we can store a map in redux, its not remended - https://github./reduxjs/redux/issues/1499.

本文标签: javascriptAdding a KeyValue to a Dictionary in ReduxStack Overflow