REDUX工具包 - 即使有错误
如果未注册用户,API将投掷401。但是,即使存在错误,ExuflaredUcer也执行满足的情况。这也发生了500和其他错误。
Exurothareucers
extraReducers: (builder) => {
builder
.addCase(login.pending, function (state) {
console.log("pending");
state.isLoading = true;
})
.addCase(login.fulfilled, (state, action) => {
console.log("fullfield");
state.isLoading = false;
state.user = action.payload;
state.isAuthenticated = true;
})
.addCase(login.rejected, (state, action) => {
console.log("rejected");
console.log(action.payload);
state.isLoading = false;
state.error = true;
state.message = action.payload;
state.user = null;
});
}
asyncthunk登录方法
export const login = createAsyncThunk("auth/login", async (user, thunkAPI) => {
try {
let user = await authService.login(user);
return user;
} catch (error) {
console.log(error);
thunkAPI.rejectWithValue(error);
}
});
登录authservice
const login = async (user) => {
const response = await axios.post(`${PROXY}/${API_URL_LOGIN}`, user);
if (response.data) {
localStorage.setItem("user", JSON.stringify(response.data.data));
}
return response.data;
};
The API throws a 401 if the user is not registered. But extraReducers execute fulfilled case even if there is an error. It's also happening for 500 and other errors.
extraReucers
extraReducers: (builder) => {
builder
.addCase(login.pending, function (state) {
console.log("pending");
state.isLoading = true;
})
.addCase(login.fulfilled, (state, action) => {
console.log("fullfield");
state.isLoading = false;
state.user = action.payload;
state.isAuthenticated = true;
})
.addCase(login.rejected, (state, action) => {
console.log("rejected");
console.log(action.payload);
state.isLoading = false;
state.error = true;
state.message = action.payload;
state.user = null;
});
}
asyncThunk login method
export const login = createAsyncThunk("auth/login", async (user, thunkAPI) => {
try {
let user = await authService.login(user);
return user;
} catch (error) {
console.log(error);
thunkAPI.rejectWithValue(error);
}
});
Login authService
const login = async (user) => {
const response = await axios.post(`${PROXY}/${API_URL_LOGIN}`, user);
if (response.data) {
localStorage.setItem("user", JSON.stringify(response.data.data));
}
return response.data;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您尝试过以下内容吗?
Have you tried the following?
用这种方式运行良好!完整的登录代码。
use this way it works well! full login code.