我无法从 createAsyncThunk 函数中捕获状态和 json 值

时间:2021-07-28 07:11:34

标签: javascript node.js reactjs react-redux redux-toolkit

usersSlice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { API } from "../axios/index";

export const signUp = ...

export const logOut = ...

export const signIn = createAsyncThunk("users/signin", async (params) => {
  try {
    const { loginData, history } = params;
    const { data } = await API.post("users/signin", loginData);
    history.push("/");
    return data;
  } catch (error) {
    console.log(error);
  }
});

const initialState = {
  usersInfo: {},
  status: "idle",
  error: null,
  existEmail: false,
};

const usersSlice = createSlice({
  name: "users",
  initialState,
  reducers: {
    handleExistEmail: (state, action) => {
      state.existEmail = action.payload;
    },
  },
  extraReducers: {
     ...
    [signIn.fulfilled]: (state, action) => {
      console.log("here is your data : ", action.payload);
      state.status = "succeeded";
      if (action.payload) {
        localStorage.setItem("user", JSON.stringify(action.payload));
      }
    },
  },
});

export default usersSlice.reducer;
export const { handleExistEmail } = usersSlice.actions;

userRouter.js

const isPasswordCorrent = await bcrypt.compare(password, user.password);

if (!isPasswordCorrent) {
  return res
    .status(404)
    .json({ message: "Password dont match" });
}

大家好。当密码和重新密码不匹配时,我想后端向我发送 status(404) 和 json({ message: "Password dont match" }) 值,我想在 {{1} 中捕获这些值} 但是 action.payload 发送给我未定义。但是如果我这次执行 [signIn.fulfilled] 而不是 return res.json({ message: "Password dont match" }),我无法从 return.status(404).json({message: "Password dont match"}) 中捕获 json({message: "Password dont match"})。为什么我必须删除 {{1 }} 部分不要未定义?

1 个答案:

答案 0 :(得分:1)

这就是 createAsyncThunk 的工作原理。这个包装器本身是一个 try/catch 块,所以在这个动作创建器函数中使用没有意义。如果此创建者函数主体中的承诺被拒绝,则您的操作将返回存储中的 rejected 子操作。所以你必须在reducer中听这个动作。或者,如果您真的想使用 try/catch 块,则在 catch 块中抛出错误。一个小例子用法:

export const exampleAsyncAction = createAsyncThunk(
  ACTION_TYPE,
  async (parameter) => {
    const result = await apicall(parameter);
    return result.doSomeLogic();
  }
);

const reducer = createReducer(
...,

[exampleAsyncAction.pending]: (state) => {
  state.loading = true;
  state.error = null;
},
[exampleAsyncAction.fulfilled]: (state, {payload}) => {
  state.result = payload;
  state.loading = false;
},
[exampleAsyncAction.rejected]: (state, {error}) => {
  state.error = error;
  state.loading = false;
},
)