我希望两个不同的切片能够交叉引用彼此的操作,如下所示:
const sliceA = createSlice({
name: "sliceA",
initialState: null,
reducers: {
someReducer: (state, action) => {
// do something
},
},
extraReducers: {
[sliceB.actions.anotherReducer]: (state, action) => {
// do something
},
},
});
const sliceB = createSlice({
name: "sliceB",
initialState: null,
reducers: {
anotherReducer: (state, action) => {
// do something else
},
},
extraReducers: {
[sliceA.actions.someReducer]: (state, action) => {
// do something else
},
},
});
Run Code Online (Sandbox Code Playgroud)
问题是我在尝试为 sliceA 设置 extraReducers 时收到 sliceB 未定义的错误。
为了清楚起见,我想将切片分开,但它们的某些操作会相互影响。
实现这一目标的好方法是什么?
您必须通过将其中一个操作的创建分解到 createActions 调用中来解决切片之间的循环依赖关系,两个 createSlice 调用都可以将其引用为 extraReducers,而无需其定义是循环的。
\n另请注意您的操作命名,然后此处的行具有误导性:\n[sliceA.actions.someReducer]: (state, action) => {
您 createSlice 正在创建actions和化简器,因此请为该操作使用一个不暗示它是化简器的名称。
\n使用createAction: https: //redux-toolkit.js.org/api/createAction
\n请参阅此处的圆形参考注释:https ://redux-toolkit.js.org/usage/usage-guide#exporting-and-using-slices
\nconst actionOnAThatAffectsB = createAction(\'B_ACTION_NAME\', function prepare(text) {\n // this function is an optional parameter to createAction.\n // only use it if you want to add to the eventual payload.\n return {\n payload: {\n text,\n id: nanoid(),\n createdAt: new Date().toISOString()\n }\n }\n})\n\nconst sliceB = createSlice({\n name: "sliceB",\n initialState: null,\n reducers: {\n actionOnBThatAffectsA: (state, action) => {\n // do main stuff on A\n },\n },\n extraReducers: {\n [sliceA.actions.someAction]: (state, action) => {\n // do other stuff.\n },\n },\n});\n\nconst sliceA = createSlice({\n name: "sliceA",\n initialState: null,\n reducers: {},\n extraReducers: {\n [sliceB.actions.actionOnBThatAffectsA]: (state, action) => {\n // do extra stuff on A\n },\n [actionOnAThatAffectsB]: (state, action) => {\n // you can\'t create the *action* here with createSlice\'s default creation through the reducers{} parameter \xe2\x80\x94 since that leads to a circular reference during creation.\n // You *are* creating the *reducer* itself here, though.\n },\n },\n});\n\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
5062 次 |
| 最近记录: |