2 回答
TA贡献1966条经验 获得超4个赞
我找到了这样做的方法。我声明变量REQUEST, SUCCESS, FAILURE并检查参数对象是否包含UserId. 如果是,它将 dispatchGET_USER_BY_ID而不是GET_USERS.
export function getUsers (params) {
let REQUEST, SUCCESS, FAILURE;
if (!_.isEmpty(params) && params.UserId) {
REQUEST = 'GET_USER_BY_ID_REQUEST';
SUCCESS = 'GET_USER_BY_ID_SUCCESS';
FAILURE = 'GET_USER_BY_ID_FAILURE';
} else {
REQUEST = 'GET_USERS_REQUEST';
SUCCESS = 'GET_USERS_SUCCESS';
FAILURE = 'GET_USERS_FAILURE';
}
return async dispatch => {
await dispatch({ type: REQUEST });
const urlParams = params ? new URLSearchParams(Object.entries(params)) : null;
return axios({
method: 'get',
url: Environment.GET_USERS+ `?${urlParams}`,
headers: { 'Content-Type': 'application/json' },
}).then (async res => {
await dispatch({ type: SUCCESS, payload: res.data.Data });
}).catch (err => {
dispatch({ type: FAILURE, error: err.toString() });
});
}
}
请注意,在我的减速器中,我只使用action.payload. 例如:
case 'GET_USERS_SUCCESS':
return { ...state, isFetching: false, userList: action.payload };
case 'GET_USER_BY_ID_SUCCESS':
return { ...state, isFetching: false, user: action.payload };
TA贡献1868条经验 获得超4个赞
你可以通过 param id 来决定动作,比如
// all users, paramId is null
// a user, paramId is xxxx
const action = paramId ?
{ type: 'GET_USER_BY_ID_SUCCESS', user: res.data.Data } :
{ type: 'GET_USERS_SUCCESS', allUsers: res.data.Data };
dispatch(action);
但是,我认为你的想法并不好。最好用两种方法来做逻辑。它是可读的。
添加回答
举报