Redux 工具包不检查被拒绝的案例

Redux toolkit not checking the rejected case

我是 redux 工具包的新手,我的 objective 是如果尝试登录的用户不是注册会员,则不让仪表板呈现。如果用户名或密码无效,我会从后端发送 500 错误,但效果很好。即使 api 响应为 500,extraReducers 也不会拒绝案例,而是转到满足的 case.My 期望,如果 api 给出错误,它将转到拒绝案件。下面是我的切片,

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";

export const currentUser = localStorage.getItem("userInfo");

const initialState = {
  currentUser: currentUser
    ? currentUser
    : {
        email: "",
        password: "",
        name: "",
        pic: "",
        confirmPassword: "",
      },
  status: null,
  isLoggedIn: currentUser ? true : false,
  userInfoFromStorage: "",
};

//login action
export const authUser = createAsyncThunk("users/authUser", async (data) => {
  const res = await axios.post("http://localhost:3010/api/users/login", data);
  return res.data;
});

//register action
export const registerUser = createAsyncThunk(
  "users/registerUser",
  async (data) => {
    try {
      const res = await axios.post("http://localhost:3010/api/users", data);
      console.log(res);
      return res.data;
    } catch (error) {
      console.log(error);
    }
  }
);

const userReducer = createSlice({
  name: "user", //to identify the slice
  initialState,
  reducers: {
    logoutUser: (state, action) => {
      state.isLoggedIn = false;
      localStorage.removeItem("userInfo");
    },
  },
  extraReducers: (builder) => {
    builder.addCase(authUser.pending, (state) => {
      console.log("pending");
      state.status = "pending";
    });
    builder.addCase(authUser.fulfilled, (state, action) => {
      state.status = "success";
      state.isLoggedIn = true;
      state.currentUser = action.payload;
      state.userInfoFromStorage = localStorage.setItem(
        "userInfo",
        JSON.stringify(action.payload)
      );
    });
    builder.addCase(authUser.rejected, (state) => {
      console.log("failed")
      state.status = "failed";
      state.isLoggedIn = false;
    });
  },
});

// Action creators are generated for each case reducer function
export const { logoutUser } = userReducer.actions;

export default userReducer.reducer;

从 loginPage 调度下面的操​​作

const submitHandler = async (e) => {
    e.preventDefault();
    dispatch(authUser({ email: email, password: password }));
    // history.push("/myNotes");
  };

在你的thunk中,你正在手动处理错误。之后的任何其他代码都无法知道出了什么问题。

这里有三个选项:

  • 不要在 createAsyncThunk 通话中 try..catch。该错误将从非标准字段中清除并最终出现在被拒绝操作的 action.error
  • 手动throw 某事。该错误将从非标准字段中清除并最终出现在被拒绝操作的 action.error
  • 手动 return thunkApi.rejectWithValue(yourError)。错误将不会被清除并落入被拒绝操作的 action.payload

您现在正在做的事情(处理错误并且 return 什么都不做)本质上等同于在您的函数中做 return undefined - 这将以 [=18= 完成的动作结束] 作为有效负载。