【发布时间】:2020-05-11 00:15:53
【问题描述】:
通常你会在一个 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)
}
使用 redux 工具包中的 createAsyncThunk,这并不是那么简单。实际上,您可以在 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 函数。我从extraReducers 案例中简单地尝试了startRecipe(state) 和startRecipe(已经为鸭子导出而解构,所以我相当确定我指的是正确的函数),但它不起作用。
我目前的解决方案是在切片之外定义 _startRecipe 并在两种情况下都引用该函数
reducers: { startRecipe: _startRecipe },
extraReducers: builder => {
builder.addCase(getRecipeFromUrl.fulfilled, _startRecipe)
}
是否有一种“更好”的方式可以让您在 slice.reducers 中定义简单操作并从 extraReducers 中的 thunk 处理程序中引用它?
【问题讨论】:
标签: redux redux-toolkit