[英]How to get custom Arg in configureStore reducer?
我想為Reducer 的依賴注入提供額外的參數。
當我創建商店時,我添加了這樣的參數。
export default configureStore({
reducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
thunk: { extraArgument: { service } },
}).concat(logger),
devTools: true,
});
我知道如何在 createAsyncThunk 函數中使用它,但我不知道如何在其他 Reducer 中使用它。 沒有第三個參數。
在以下情況下,沒有第三個因素。
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
logout: (state, action, third) => {
// third is undefiend!!! it doesn't get value.
// but createAsyncThunk does
const { extra} = third;
const { service } = extra;
service.authService.logout();
return {
isLoggedIn: false,
userId: null,
profile: {
name: null,
},
token: null,
};
}
},
像你的service.authService.logout();
是副作用,Redux reducer 中決不允許出現副作用。 reducer 只允許讀取state
和action
以及(在createSlice
的情況下)修改state
。 不允許有其他副作用。 所以在你的減速器中不會有這樣的東西。
不過,您可以為此使用偵聽器中間件。
listenerMiddleware.startListening({
actionCreator: authSlice.actions.logout,
effect: async (action, listenerApi) => {
listenerApi.extra.authService.logout()
},
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.