我有一个 redux-thunk (redux-toolkit) 问题,当我调度操作 logIn 时,console.log 正在工作,但是
Auth
文件中的这个功能 apiInstance.ts
不起作用
这是我设置的商店和减速器
// my config's store
import { ThunkAction, thunk } from "redux-thunk";
import { Action, configureStore, getDefaultMiddleware } from "@reduxjs/toolkit";
import rootReducer from "../reducer/index.ts";
const store = configureStore({
reducer: rootReducer,
middleware: [...getDefaultMiddleware(), thunk],
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export type AppThunk = ThunkAction<void, RootState, null, Action<any>>;
export default store;
// my store
import { combineReducers } from "redux";
import AuthReducer from "./auth/index.ts";
import PathVariableReducer from "./pathVariable/index.ts";
import codeRunner from "./codeRunner/index.ts";
import toastMessage from "./toastMessage/index.ts";
import dataDefine from "./dataDefine.ts";
const rootReducer = combineReducers({
AuthReducer,
PathVariableReducer,
codeRunner,
toastMessage,
dataDefine,
});
export default rootReducer;
// my reducer
import { createSlice } from "@reduxjs/toolkit";
import {
Auth,
LogOut,
ResetPasswordEmail,
UpdateInfor,
} from "../../../service/apiInstance";
const AuthReducer = createSlice({
name: "auth",
initialState: {},
reducers: {
logIn: (state, action) => {
console.log("test") // working
Auth(action.payload, "login"); // not working
},
logOut: (state, action) => LogOut(),
register: (state, action) => Auth(action.payload, "register"),
forgotPassword: (state, action) =>
ResetPasswordEmail({ email: action.payload }),
resetPassword: (state, action) =>
ResetPasswordEmail({
oldPassword: action.payload,
newPassword: action.payload,
}),
updateInfor: (state, action) => UpdateInfor(action.payload),
},
});
这是我的功能
Auth
在apiInstance.ts
// not working
import axios from "axios";
import { TOAST_MESSAGE } from "../redux/reducer/toastMessage";
import { Dispatch } from "redux";
import { AppDispatch, AppThunk } from "../redux/store";
import { getPostSuccess } from "../redux/reducer/dataDefine";
export const Auth = (req: object, auth: string): AppThunk => async ( // my function
dispatch: AppDispatch
) => {
console.log("test successful");
await fetchCSRFToken();
try {
const response = await axiosInstance.post(`/${auth}`, req);
localStorage.setItem("login", "true");
localStorage.setItem("name", JSON.stringify(response.data.name));
localStorage.setItem("email", JSON.stringify(response.data.email));
window.location.replace("/");
console.log(response.data);
} catch (error) {
dispatch(getPostSuccess);
dispatch(
TOAST_MESSAGE({
type: "error",
content: error,
duration: 5,
})
);
throw new Error("Authentication failed");
}
};
我正在尝试任何情况,但它不起作用,那么在这种情况下我应该做什么?
使用
import { useDispatch, useSelector } from 'react-redux';
而不是import { Dispatch } from "redux";
开火行动