如何在 redux-toolkit 的 createSlice 的 prepare 方法中进行异步调用?
How to make async calls in prepare method of createSlice of redux-toolkit?
我有以下createSlice
方法。我查看了 createSlice
的 documentation,他们提供了使用 prepare
方法自定义动作创建的选项。
我正在尝试进行 API 调用,但是在 API 响应之前触发了 reducer。因此我的 action.payload
仍然是 undefined
.
可以prepare
进行异步调用吗?
PS:我不想在单独的 function/file 中维护我的自定义动作创建器。使用createSlice
的目的是提高代码的可维护性。
export const authReducers = createSlice({
name: "auth",
initialState: { ...initialState },
reducers: {
loginToConsole: {
reducer: (state, action) => {
console.log("Reducer Called", action);
state.isLoggedIn = !state.isLoggedIn;
},
prepare: async (credentials) => {
let response = await axios.post(
`${apiEndPoint}/api/auth/login`,
credentials
);
console.log(response);
return { payload: { ...response.data } };
},
},
},
});
不,不能。 prepare
被同步调用。
你应该为此使用 thunk - 参见 This Chapter of the official Redux tutorial
就是说,没有什么能阻止您在同一个文件中编写您的 thunk。很多人都这样做。
我有以下createSlice
方法。我查看了 createSlice
的 documentation,他们提供了使用 prepare
方法自定义动作创建的选项。
我正在尝试进行 API 调用,但是在 API 响应之前触发了 reducer。因此我的 action.payload
仍然是 undefined
.
可以prepare
进行异步调用吗?
PS:我不想在单独的 function/file 中维护我的自定义动作创建器。使用createSlice
的目的是提高代码的可维护性。
export const authReducers = createSlice({
name: "auth",
initialState: { ...initialState },
reducers: {
loginToConsole: {
reducer: (state, action) => {
console.log("Reducer Called", action);
state.isLoggedIn = !state.isLoggedIn;
},
prepare: async (credentials) => {
let response = await axios.post(
`${apiEndPoint}/api/auth/login`,
credentials
);
console.log(response);
return { payload: { ...response.data } };
},
},
},
});
不,不能。 prepare
被同步调用。
你应该为此使用 thunk - 参见 This Chapter of the official Redux tutorial
就是说,没有什么能阻止您在同一个文件中编写您的 thunk。很多人都这样做。