通常在一个 thunk 中,您最终会调用其他操作:
const startRecipe = {type: "startRecipe"}
const reducer = (state, action) => {
if (action.type === "startRecipe") {
state.mode = AppMode.CookRecipe
}
}
const getRecipeFromUrl = () => async dispatch => {
const res = await Parser.getRecipeFromUrl(url)
dispatch(startRecipe)
}
在createAsyncThunk
redux 工具包中,这并不是那么简单。实际上,您可以从结果中的操作中改变状态extraReducers
:
export const getRecipeFromUrl = createAsyncThunk('getRecipeFromUrl',
async (url: string): Promise<RecipeJSON> => await Parser.getRecipeFromUrl(url)
)
const appStateSlice = createSlice({
name: 'app',
initialState: initialAppState,
reducers: {},
extraReducers: ({ addCase }) => {
addCase(getRecipeFromUrl.fulfilled, (state) => {
state.mode = AppMode.CookRecipe
})
}
})
但我也希望有非异步方式来启动配方,这将需要在切片中使用减速器:
reducers: {
startRecipe(state): state.mode = AppState.CookRecipe
},
为了避免在两个地方编写相同的代码,我希望能够从 thunk 处理程序中调用简单的 reducer 函数。我从案例中简单地尝试了startRecipe(state)
和startRecipe
(它已经为鸭子导出而解构,所以我相当确定我指的是正确的函数),extraReducers
但它不起作用。
我目前的解决方案是_startRecipe
在切片之外定义,并在两种情况下都引用该函数
reducers: { startRecipe: _startRecipe },
extraReducers: builder => {
builder.addCase(getRecipeFromUrl.fulfilled, _startRecipe)
}
是否有一种“更好”的方式可以在您的中定义简单操作slice.reducers
并从 thunk 处理程序中引用它extraReducers
?