javascript - redux 到 redux-toolkit 重构
问题描述
有人可以解释为什么当我从服务器收到 401 错误时,这段代码会调度“actions.loginSuccess”吗?它不应该去“捕获” axios 请求的一部分吗?
在我没有redux工具包功能之前
const login = ({username, password}) => async dispatch => {
await axios.post(`${API_URL}/token/`, {username, password})
.then(response => {
dispatch(actions.loginSuccess({ client_id: response?.data.client_id }))
history.push('/')
})
.catch(e => {
dispatch(actions.loginError({ error: String(e) }))
})
}
//actions.js
const login = createAction('@USER/login')
const loginSuccess = createAction('@USER/login-success')
const loginError = createAction('@USER/login-error')
export const actions = {
login,
loginSuccess,
loginError
}
//reducers.js
export const userReducer = createReducer(initialState, builder => {
builder.addCase(actions.login, draft => {
draft.loading = true
})
builder.addCase(actions.loginSuccess, (draft, action) => {
draft.loading = false
draft.isLoggedIn = true
draft.data = { ...draft.data, client_id : action.client_id}
})
builder.addCase(actions.loginError, (draft, action) => {
draft.loading = false
draft.error = action.payload.error
draft.isLoggedIn = false
draft.isSignedup = false
})
}
解决方案
有人可以解释为什么当我从服务器收到 401 错误时,这段代码会调度“actions.loginSuccess”吗?它不应该去“捕获” axios 请求的一部分吗?
// there's a difference beetween HTTP Status Code and Server Response Body Code.
// if HTTP status code is not 200, it should dispatched loginError()
// if HTTP status code is 200, and theres a response body JSON
// e.g
const resp = {
statusCode: 401,
message: 'unauthorized',
}
// You must make if conditions to handle that error code
这是您的代码的 redux-toolkit 版本,用于处理 HTTP 状态代码 401 或正文响应代码
// import axios & history
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
data: {},
loading: false,
isLoggedIn: false,
isSignedup: false,
};
// Reducers
const userSlice = createSlice({
name: '@USER',
initialState: initialState,
reducers: {
loginStart(state) {
state.loading = true;
},
loginSuccess(state, action) {
state.data = {
...state.data,
client_id: action.payload.client_id
};
state.loading = false;
state.isLoggedIn = true;
},
loginError(state, action) {
state.loading = false;
state.error = action.payload.error;
state.isLoggedIn = false;
state.isSignedup = false;
},
},
});
// actions
export const { loginStart, loginSuccess, loginError } = userSlice.actions;
export default userSlice.reducer;
export const login = ({ username, password }) => async (dispatch) => {
dispatch(loginStart());
try {
const response = await axios.post(`${API_URL}/token/`, {
username,
password,
});
if(response && response.statusCode !== 200){
return dispatch(loginError({ error: response.message }));
}
dispatch(loginSuccess({ client_id: response?.data.client_id }));
history.push('/');
} catch (e) {
dispatch(loginError({ error: String(e) }));
}
};
不要忘记添加userSlice
到configureStore()
const reducer = {
"@USER": userReducers, //got from export default userSlice.reducer
};
export default configureStore({
reducer,
middleware,
devTools: process.env.NODE_ENV !== 'production',
});
推荐阅读
- angular - 使用 Angular 从 html 和 css 创建可搜索的 pdf - 不适用于 jspdf
- angular - Angular 组件 UI
- tomcat - 从 Jhipster 3.9.0 中删除码头服务器
- filter - 如何在 fluent-bit 中覆盖 rewrite_tag
- ms-word - 如何在 MS-Word 加载项中启用/禁用自定义加载项按钮?
- c++ - 使用 Visual Studo for OneCore 编译时缺少 concrt.lib
- c++ - 如何将 constexpr 字符串文字传递给其他函数
- queue - Chronicle Queue cq4 文件大小不正确
- c# - 检查gridview中的日期是否与当前日期匹配
- android - Flutter 安装问题,无法在 PC 中加载或找到主类