标准化API数据以在Redux中使用

时间:2018-06-27 19:48:17

标签: javascript reactjs redux normalizr

我有以下来自API的数据:

const data = {
  id: 1,
  name: 'myboard',
  columns: [
    {
      id: 1,
      name: 'col1',
      cards: [
        { id: 1, name: 'card1' },
        { id: 2, name: 'card2' }
      ]
    },
    {
      id: 2,
      name: 'col2',
      cards: [
        { id: 3, name: 'card3' },
        { id: 4, name: 'card4' }
      ]
    },
  ]
}

如您所见,本质上有3个嵌套级别。顶层包含一个idname和一个列表columns。每个column包含一个idname和一个cards的列表。每个card都有一个idname

我希望将数据归一化,如here所示在Redux中使用。我正在使用normalizr进行以下操作:

const card = new schema.Entity('cards');
const column = new schema.Entity('columns', {
  cards: [card]
});
const board = new schema.Entity('boards', {
  columns: [column]
});

normalize(data, board)

结果如下:

{
  "entities": {
    "cards": {
      "1": {
        "id": 1,
        "name": "card1"
      },
      "2": {
        "id": 2,
        "name": "card2"
      },
      "3": {
        "id": 3,
        "name": "card3"
      },
      "4": {
        "id": 4,
        "name": "card4"
      }
    },
    "columns": {
      "1": {
        "id": 1,
        "name": "col1",
        "cards": [1, 2]
      },
      "2": {
        "id": 2,
        "name": "col2",
        "cards": [3, 4]
      }
    },
    "boards": {
      "1": {
        "id": 1,
        "name": "myboard",
        "columns": [1, 2]
      }
    }
  },
  "result": 1
}

我似乎无法弄清楚如何将每个部分(即cardscolumnsboards)分成两个部分,即byIdallIds(如上述Redux文章所述。)

从本质上讲,这是为了使React应用程序中的排序,排序等更加容易。我使用的是最新版本的normalizr(3.2.4)。

1 个答案:

答案 0 :(得分:1)

Here is a CodeSandbox with an example,介绍如何设置化简器以处理归一化状态。

从本质上讲,您将为每个实体最终得到类似这样的东西:

// lambda or function - whatever your preference is
const cardsById = (state = {}, action) => {
  // if, case, handler function - whatever your preference is
  if (action.type === 'ADD_DATA') { // or whatever your initial data load type is
    return { ...state, ...action.payload.cards }
  }
  return state
}

const allCards = (state = [], action) => {
  if (action.type === 'ADD_DATA') { // or whatever your initial data load type is
    return [...state, ...Object.keys(action.payload.cards)]
  }
  return state
}

const cards = combineReducers({
  byId: cardsById,
  allIds: allCards
})

,然后将所有这些组合在一起:

export default combineReducers({
  cards,
  columns,
  boards
})

为此创建的动作如下:

const addData = ({ entities }) => ({
  type: 'ADD_DATA',
  payload: entities // note the rename - this is not required, just my preference
})

// I used a thunk, but theory is the the same for your async middleware of choice
export const getData = () => dispatch => dispatch(addData(normalize(data, board)))

希望这会有所帮助。请记住,在添加或删除实体时,您将需要同时维护每个实体的byIdallIds