4

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

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 的错误。

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

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

4

1 回答 1

4

您必须通过将其中一个操作的创建分解到 createActions 调用中来解决切片之间的循环依赖关系,两个 createSlice 调用都可以将其作为 extraReducers 引用,而不需要它们的定义是循环的。

还要注意您的操作命名,然后这里的行具有误导性: [sliceA.actions.someReducer]: (state, action) => {

您 createSlice 正在制作actionreducers,因此请使用不暗示它是 reducer 的操作名称。

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

于 2020-08-30T01:51:27.037 回答