从 createAsyncThunk 调用其他操作

Jon*_*man 0 redux redux-toolkit

通常在 thunk 中你最终会调用其他操作:

\n\n
const startRecipe = {type: "startRecipe"}\n\nconst reducer = (state, action) => {\n  if (action.type === "startRecipe") { \n    state.mode = AppMode.CookRecipe\n  }\n}\n\nconst getRecipeFromUrl = () => async dispatch => {\n  const res = await Parser.getRecipeFromUrl(url)\n  dispatch(startRecipe)\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

在 redux 工具包中createAsyncThunk,这并不是那么简单。事实上,您可以通过以下操作来改变状态extraReducers

\n\n
export const getRecipeFromUrl = createAsyncThunk(\'getRecipeFromUrl\',\n  async (url: string): Promise<RecipeJSON> => await Parser.getRecipeFromUrl(url)\n)\n\nconst appStateSlice = createSlice({\n  name: \'app\',\n  initialState: initialAppState,\n  reducers: {},\n  extraReducers: ({ addCase }) => {\n    addCase(getRecipeFromUrl.fulfilled, (state) => {\n      state.mode = AppMode.CookRecipe\n    })\n  }\n})\n
Run Code Online (Sandbox Code Playgroud)\n\n

但我也希望有非异步方式来启动配方,这将需要切片中的减速器:

\n\n
  reducers: {\n    startRecipe(state): state.mode = AppState.CookRecipe\n  },\n
Run Code Online (Sandbox Code Playgroud)\n\n

为了避免在两个地方编写相同的代码,我希望能够从 thunk 处理程序调用简单的减速器函数。我尝试简单地startRecipe(state)从案例中尝试startRecipe(它已被解构以用于鸭子导出,因此我\xe2\x80\x99m相当确定我指的是正确的函数),extraReducers但它不起作用。

\n\n

_startRecipe我当前的解决方案是在切片外部定义并在两种情况下仅引用该函数

\n\n
  reducers: { startRecipe: _startRecipe },\n  extraReducers: builder => {\n    builder.addCase(getRecipeFromUrl.fulfilled, _startRecipe)\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

是否有一种“更好”的方法可以在您的中定义简单操作slice.reducers并从 thunk 处理程序中引用它extraReducers

\n

ale*_*ero 7

的第二个参数payloadCreatorthunkAPI( doc ),您可以从中分派cookRecipe操作。

interface ThunkApiConfig {
  dispatch: AppDispatch,
  state: IRootState,
}

export const getRecipeFromUrl = createAsyncThunk('getRecipeFromUrl',
  async (url: string, thunkAPI: ThunkApiConfig): Promise<RecipeJSON> => {
    await Parser.getRecipeFromUrl(url)
    return thunkAPI.dispatch(cookRecipeActionCreator())
  }
)
Run Code Online (Sandbox Code Playgroud)