所以我向前跑并规范化Reducer中的所有实体,这意味着每个reducer都有一个单独的 entities
对象 . 我现在意识到,一个reducer在其中包含所有实体更有意义,然后只将ID(例如currentUser或其他东西)存储在单独的reducer中 .
这种方法对于从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
}
}
}
}
}
-
我们可以't work this out earlier in an action, as actions can'知道状态是什么
-
我们可以't do this in a reducer that doesn' t包含相关实体,因为Reducer可以't/shouldn't访问其他reducer
-
在
entities
减速机中做所有这些都感觉不对,因为它会变得非常混乱
有人有任何见解吗?
1 回答
一些想法:
动作创建者可以知道状态是什么,因为
redux-thunk
允许您编写有权访问getState()
的函数 .切片减少器可以访问其他状态切片中的数据,每the Redux FAQ entry on sharing state between slice reducers .
除了Normalizr之外,还有许多其他选项用于管理Redux中的规范化状态 . 我个人是Redux-ORM library的粉丝,并在我的"Practical Redux" tutorial series中广泛地写了这篇文章 .
在那个系列中,我特别展示了writing "feature reducers" that have access to the entire root state tree的方法,以及generic logic for updating any entity based on its type and ID .
最后,您可能还想查看immer immutable update library以简化更新嵌套状态 .