我正在尝试达到我的错误状态,但是每个我都有一个未经授权的错误,这只是我的切片的待处理状态,如何调用而不是被拒绝的状态。这是我所在州的代码 首先我尝试使用 axios 对用户进行身份验证,如果有数据,它会发送回数据,如果没有,它会发送错误数据。
import { PayloadAction, createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { IUser } from "../../../data/products";
import axios from "axios";
//my states
type State = {
loading: boolean;
user: IUser | null;
error: Error | undefined;
};
const initialState: State = {
loading: false,
user: JSON.parse(localStorage.getItem("userInfo")!) || null,
error: undefined,
};
type Props = {
email: string;
password: string;
};
// Request to try try to log
export const authUser = createAsyncThunk(
"auth/login",
async ({ email, password }: Props, { rejectWithValue }) => {
if (typeof email !== "string" || typeof password !== "string") {
return rejectWithValue(new Error("Email and password are required"));
}
try {
//set to locastorage
const { data } = await axios({
method: "post",
url: "/api/auth/login",
headers: { "Content-Type": "application/json" },
data: {
email: email.trim(),
password: password.trim(),
},
});
console.log(data);
localStorage.setItem("userInfo", JSON.stringify(data));
return data;
} catch (error: unknown) {
if (typeof error === "object" && error !== null && "message" in error) {
return error.message;
}
return error;
}
}
);
// my reducer
export const userSlice = createSlice({
name: "userAuth",
initialState,
reducers: {
logoutAction: (state) => {
state.loading = false;
state.user = null;
},
},
extraReducers: (builder) => {
builder
.addCase(authUser.pending, (state) => {
state.loading = true;
})
.addCase(
authUser.fulfilled,
(state, { payload }: PayloadAction<IUser>) => {
state.loading = false;
state.user = payload;
}
)
.addCase(authUser.rejected, (state, { payload }) => {
console.log("Auth User Rejected:", payload);
state.loading = false;
state.error = payload as Error;
});
},
});
export default userSlice.reducer;
达到错误时更改错误状态
当 POST 请求处理期间出现错误或 Promise 拒绝时,该操作将捕获它并将错误作为“已解决”值返回。换句话说,通过使用
return error.message
或 return error
authUser
Thunk 得以实现。如果您想针对 authUser.rejected
情况返回 POST 处理错误,则 Thunk 需要拒绝。
export const authUser = createAsyncThunk(
"auth/login",
async ({ email, password }: Props, { rejectWithValue }) => {
if (typeof email !== "string" || typeof password !== "string") {
return rejectWithValue(new Error("Email and password are required"));
}
try {
const { data } = await axios({
method: "POST",
url: "/api/auth/login",
headers: { "Content-Type": "application/json" },
data: {
email: email.trim(),
password: password.trim(),
},
});
localStorage.setItem("userInfo", JSON.stringify(data));
return data; // <-- fulfill
} catch (error: unknown) {
if (typeof error === "object" && error !== null && "message" in error) {
return rejectWithValue(error.message); // <-- reject
}
return rejectWithValue(error); // <-- reject
}
}
);