首页 > 解决方案 > Modelling data based on a time range using redux/normalizr

问题描述

I've have the following data coming from a node backend:

Endpoint:

/user/:id?startDate=2011-10-05T14:48:00.000Z&endDate=2011-10-05T14:48:00.000Z

[
   {
      "name": "Tom",
      "createdAt": "2011-10-05T14:48:00.000Z",
      "updatedAt": "2011-10-05T14:48:00.000Z",
      ...
      "metadata": {
         "activeHours": 134.45,
         "afkHours": 134.45
      }
   },
   {
      ...
   }
]

In this data, the only thing modified between date changes is activeHours and afkHours.

These users and the date that the endpoint was called with must be synced across all pages.

The simple approach would be to put this in a users reducer, something like:

{
   users: [...],
   startDate: "",
   endDate: ""
}

However I'm currently using normalizr with these users and with that I have a single action named ADD_ENTITIES. Having an entities reducer seems very beneficial as we do have other entities that can be nicely normalized with these users, however I don't want to pollute the entities state with almost "tacked on" startDate and endDate to sync across all pages.

On to my question:

Is there a better way to model this problem using normalizr, Where your key is not only ID but also a date range?

Or should I look at breaking this out into a separate reducer as above?

标签: reactjsreduxnormalizr

解决方案


不确定我是否完全理解这里的问题。

startDateendDate字段对于每个用户是否不同?如果是,那么您可能需要在这些用户的规范化实体对象中添加这些字段。

如果这些是所有用户的公共字段,您可以创建一个名为userDateRange包含这两个键的单独实体。它不需要标准化,因为它们是原始字段。

{
  "entities": {
    "user": {
      "byId": {
        "user1": {},
        "user2": {}
      },
      "allIds": [
        "user1",
        "user2"
      ]
    }
  },
  "ui": {
    "userDateRange": {
      "start": "2011-10-05T14:48:00.000Z",
      "end": "2011-10-05T14:48:00.000Z"
    }
  }
}

推荐阅读