【发布时间】:2021-10-03 22:20:51
【问题描述】:
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" });
}
大家好。当密码和重新密码不匹配时,我想后端向我发送状态(404)和json({消息:“密码不匹配”})值,我想在[signIn.fulfilled]中捕获这些值但是action.payload 发送给我未定义。但如果我这次使用 return res.json({ message: "Password dont match" }) 而不是 return.status(404).json({message: "Password dont match"}),我无法从[signIn.fulfilled] 中捕获json({message: "Password dont match"})。为什么我必须删除.status(404) 部分才能避免未定义?
【问题讨论】:
-
缺少相关信息。
res对象在哪里以及什么构建,为什么必须在路由器中定义响应的状态?您显然正在使用 Axios,因此这些调用如果导致 404,将在其错误响应对象中包含状态信息,您可以在 thunk 函数中捕获这些信息。
标签: javascript node.js reactjs react-redux redux-toolkit