Ebr*_*mid 1 reactjs redux redux-thunk react-redux redux-toolkit
如果用户未注册,API 会抛出 401。但即使有错误,extraReducers 也会执行已完成的情况。500 和其他错误也会发生这种情况。
额外减速器
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;
});
}
Run Code Online (Sandbox Code Playgroud)
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);
}
});
Run Code Online (Sandbox Code Playgroud)
登录 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;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4842 次 |
| 最近记录: |