【发布时间】:2020-03-31 15:50:18
【问题描述】:
我正在使用带有 react 和 redux-thunk 作为中间件的 Redux。
当我发出 http 请求时,我必须在我的 thunk 中调度三个操作。 我将使用我的身份验证示例。
这是我的行动:
export const loginSuccess = () => ({
type: AUTH_LOGIN_SUCCESS,
})
export const loginFailure = (errorMessage) => ({
type: AUTH_LOGIN_FAILURE,
errorMessage,
})
export const loginRequest = () => ({
type: AUTH_LOGIN_REQUEST,
})
这是结合了以上三个动作的thunk:
export const login = (credentials) => dispatch => {
dispatch(loginRequest())
const options = {
method: 'post',
url: `${ENDPOINT_LOGIN}?username=${credentials.username}&password=${credentials.password}`,
}
axiosInstance(options)
.then(response => {
dispatch(loginSuccess())
dispatch(loadUser(response.data)) // I have separate action for user and separate reducer.
window.localStorage.setItem(ACCESS_TOKEN_KEY, response.data.token)
})
.catch(error => {
return dispatch(loginFailure(error))
})
}
这是我的减速器:
const initialState = {
pending: false,
error: false,
errorMessage: null,
}
export const loginReducer = (state = initialState, action) => {
switch (action.type) {
case AUTH_LOGIN_SUCCESS:
return {
...state,
pending: false,
error: false,
errorMessage: null,
}
case AUTH_LOGIN_FAILURE:
const { errorMessage } = action
return {
...state,
pending: false,
error: true,
errorMessage,
}
case AUTH_LOGIN_REQUEST:
return {
...state,
pending: true,
}
default:
return state
}
}
当我发送另一个请求时,我必须做几乎完全相同的事情,例如在注销的情况下。我觉得我在重复自己很多,必须有更好的方法。
我需要知道处理此问题的最佳做法是什么。
如有任何其他更正和建议,我们将不胜感激。
【问题讨论】:
标签: redux redux-thunk