gpt4 book ai didi

redux-toolkit - Redux 工具包 : Have two slices reference each other's actions in extraReducers?

转载 作者:行者123 更新时间:2023-12-04 12:24:31 28 4
gpt4 key购买 nike

我想要两个不同的切片来交叉引用彼此的 Action ,如下所示:

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
},
},
});

问题是我在尝试为 sliceA 设置 extraReducers 时收到了 sliceB 未定义的错误。

为了清楚起见,我想将切片分开,但它们的某些操作会相互影响。

什么是实现这一目标的好方法?

最佳答案

您必须通过将其中一个操作的创建分解为 createActions 调用来解决切片之间的循环依赖性,这两个 createSlice 调用都可以作为 extraReducers 引用,而无需它们的定义是循环的。
还要注意你的 Action 命名,然后这里的行是误导性的:[sliceA.actions.someReducer]: (state, action) => {您 createSlice 正在制作 Action 和 reducer ,因此使用不暗示它是 reducer 的 Action 名称。
使用 createAction:https://redux-toolkit.js.org/api/createAction
请参阅此处的循环引用注释:https://redux-toolkit.js.org/usage/usage-guide#exporting-and-using-slices

const actionOnAThatAffectsB = createAction('B_ACTION_NAME', function prepare(text) {
// this function is an optional parameter to createAction.
// only use it if you want to add to the eventual payload.
return {
payload: {
text,
id: nanoid(),
createdAt: new Date().toISOString()
}
}
})

const sliceB = createSlice({
name: "sliceB",
initialState: null,
reducers: {
actionOnBThatAffectsA: (state, action) => {
// do main stuff on A
},
},
extraReducers: {
[sliceA.actions.someAction]: (state, action) => {
// do other stuff.
},
},
});

const sliceA = createSlice({
name: "sliceA",
initialState: null,
reducers: {},
extraReducers: {
[sliceB.actions.actionOnBThatAffectsA]: (state, action) => {
// do extra stuff on A
},
[actionOnAThatAffectsB]: (state, action) => {
// you can't create the *action* here with createSlice's default creation through the reducers{} parameter — since that leads to a circular reference during creation.
// You *are* creating the *reducer* itself here, though.
},
},
});

关于redux-toolkit - Redux 工具包 : Have two slices reference each other's actions in extraReducers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61138775/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com