Normalizr - 我应该在哪里修改一个实体?
Normalizr - where would I modify an entity?
所以我 运行 提前规范化了我的 reducer 中的所有实体,这意味着每个 reducer 都有一个单独的 entities
对象。我现在意识到 one reducer 在其中包含 all 实体更有意义,然后只需将 ID(例如 currentUser 或其他东西)存储在单独的减速机。
这种方法对于从 API 响应中合并实体是完全有意义的,但我不知道如何 更改 任何实体。
比如我应该在哪里做这样的操作?
case SUBSCRIBER_TOGGLED: {
let projectSubscriberIDs = cloneDeep(action.payload.project.subscriberIDs);
let indexIfExists = projectSubscriberIDs.indexOf(action.payload.user.id);
if(indexIfExists != -1){
projectSubscriberIDs.splice(indexIfExists, 1);
}else{
projectSubscriberIDs.push(action.payload.user.id);
}
return {
...state,
entities: {
...state.entities,
projects: {
...state.entities.projects,
[action.payload.project.id]: {
...action.payload.project,
subscriberIDs: projectSubscriberIDs
}
}
}
}
}
- 我们无法在操作中更早地解决这个问题,因为操作不知道状态是什么
- 我们不能在不包含相关实体的 reducer 中执行此操作,因为 reducer 不能t/shouldn无法访问其他 reducer
- 在
entities
reducer 中做所有这些感觉是错误的,因为它会变得一团糟
这里有人有任何见解吗?
一些想法:
- 动作创建者可以知道什么是状态,因为
redux-thunk
允许您编写可以访问getState()
的函数。
根据 the Redux FAQ entry on sharing state between slice reducers,- 切片缩减器 可以 访问其他状态切片中的数据。
- 除了 Normalizr 之外,还有很多其他选项可用于管理 Redux 中的规范化状态。我个人是 Redux-ORM library, and have written about it extensively in my "Practical Redux" tutorial series 的粉丝。
- 在那个系列中,我专门展示了 writing "feature reducers" that have access to the entire root state tree, as well as generic logic for updating any entity based on its type and ID 的方法。
- 最后,您可能还想查看
immer
immutable update library 以简化嵌套状态的更新。
所以我 运行 提前规范化了我的 reducer 中的所有实体,这意味着每个 reducer 都有一个单独的 entities
对象。我现在意识到 one reducer 在其中包含 all 实体更有意义,然后只需将 ID(例如 currentUser 或其他东西)存储在单独的减速机。
这种方法对于从 API 响应中合并实体是完全有意义的,但我不知道如何 更改 任何实体。
比如我应该在哪里做这样的操作?
case SUBSCRIBER_TOGGLED: {
let projectSubscriberIDs = cloneDeep(action.payload.project.subscriberIDs);
let indexIfExists = projectSubscriberIDs.indexOf(action.payload.user.id);
if(indexIfExists != -1){
projectSubscriberIDs.splice(indexIfExists, 1);
}else{
projectSubscriberIDs.push(action.payload.user.id);
}
return {
...state,
entities: {
...state.entities,
projects: {
...state.entities.projects,
[action.payload.project.id]: {
...action.payload.project,
subscriberIDs: projectSubscriberIDs
}
}
}
}
}
- 我们无法在操作中更早地解决这个问题,因为操作不知道状态是什么
- 我们不能在不包含相关实体的 reducer 中执行此操作,因为 reducer 不能t/shouldn无法访问其他 reducer
- 在
entities
reducer 中做所有这些感觉是错误的,因为它会变得一团糟
这里有人有任何见解吗?
一些想法:
- 动作创建者可以知道什么是状态,因为
redux-thunk
允许您编写可以访问getState()
的函数。
根据 the Redux FAQ entry on sharing state between slice reducers, - 切片缩减器 可以 访问其他状态切片中的数据。
- 除了 Normalizr 之外,还有很多其他选项可用于管理 Redux 中的规范化状态。我个人是 Redux-ORM library, and have written about it extensively in my "Practical Redux" tutorial series 的粉丝。
- 在那个系列中,我专门展示了 writing "feature reducers" that have access to the entire root state tree, as well as generic logic for updating any entity based on its type and ID 的方法。
- 最后,您可能还想查看
immer
immutable update library 以简化嵌套状态的更新。