Redux请求状态。简化样板
我将Redux与react和Redux thunk一起用作中间件 当我发出http请求时,我必须在thunks中分派三个操作。 我将使用我的auth示例 以下是我的行动:Redux请求状态。简化样板,redux,redux-thunk,Redux,Redux Thunk,我将Redux与react和Redux thunk一起用作中间件 当我发出http请求时,我必须在thunks中分派三个操作。 我将使用我的auth示例 以下是我的行动: export const loginSuccess = () => ({ type: AUTH_LOGIN_SUCCESS, }) export const loginFailure = (errorMessage) => ({ type: AUTH_LOGIN_FAILURE, errorMessa
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
}
}
当我发送另一个请求时,我必须做几乎完全相同的事情,例如在注销的情况下。我觉得我重复了很多次,一定有更好的方法
我需要知道处理这个问题的最佳做法是什么
任何其他更正和建议将不胜感激。如果您正在寻找“即用”解决方案,请查看:
- (但是它是用js(不是TS)编写的,并且没有针对这个库的@types定义)
- 减速机厂
- 三个行动的工厂
- 图恩工厂
const actions=createActions('My request name');
const reducer=createReducer(操作);
...
const thunk=createThunk(配置);
甚至可以将它们结合起来:
const{actions,reducer,thunk}=createRequestState('Name…',config);
。。。但这只是一个想法。如果您正在寻找“即用”解决方案,请查看:
- (但是它是用js(不是TS)编写的,并且没有针对这个库的@types定义)
- 减速机厂
- 三个行动的工厂
- 图恩工厂
const actions=createActions('My request name');
const reducer=createReducer(操作);
...
const thunk=createThunk(配置);
甚至可以将它们结合起来:
const{actions,reducer,thunk}=createRequestState('Name…',config);
。。。但这只是一个想法