【发布时间】:2017-10-31 16:06:40
【问题描述】:
我正在开发一个有很多异步操作的应用程序。我想使用 redux-saga,但大多数人坚持要继续使用 redux-thunk。在 redux-thunk 中,在每个动作中,我们必须使用 then、dispatch、catch 等进行异步操作。这使得看起来动作如此混乱,并且会重复大量代码。我想创建一个通用的 dataLoader 来使用 redux-thunk 和 axios 但不能同时考虑 post(可能是令牌)和 get 选项。
这是我的尝试:
export class Company {
/**
* Generic api data loader
*/
static dataLoader(apiUri, onSuccess, onError, data, ...actionArguments) {
const requestURL = `${API_BASE}${apiuri}`;
try {
let options;
if (data !== undefined) {
// if we have data to post
options = {
method: 'POST',
url: requestURL,
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
};
}
}
return function(dispatch) {
axios(options)
.then(response => {
dispatch({
type: onSucess,
payload: response.data
});
})
.catch(error => {
dispatch({ type: onError, payload: err});
});
}
}
static get(apiUri, onSuccess, onError, ...actionArguments) {
return this.dataLoader(apiUri, onSuccess, onError, undefined, ...actionArguments);
}
/*
* Shorthand POST function
*/
static post(apiUri, onSuccess, onError, data, ...actionArguments) {
return this.dataLoader(apiUri, onSuccess, onError, data, ...actionArguments);
}
}
我想将以下代码转换为进一步的代码:
export function showResultofApartment() {
return (dispatch) => {
dispatch({ type: 'APARTMENT_FETCH_START' });
const token = localStorage.getItem('token');
return axios.get(`${API_URL}/newoffers/apartment/`)
.then((response) => {
console.log('response apart', response.data);
dispatch({ type: 'APARTMENT_FETCH_SUCCESS', payload: response.data });
})
.catch((err) => {
dispatch({ type: 'APARTMENT_FETCH_FAILURE', payload: err });
});
};
}
这样或比这更有效率:
export function showResultofApartment() {
return(dispatch) => {
dispatch({ type: APARTMENT_FETCH_START });
const token = localStorage.getItem('token');
return Company.get('/apartments', APARTMENT_FETCH_SUCCESS, APARTMENT_FETCH_ERROR);
// if post then Company.post('/apartment', APARTMENT_POST_SUCCESS, APARTMENT_POST_ERROR, data)
}
}
这种方式只考虑发布请求(如果数据!==未定义)。我应该如何有效地处理获取和发布?
【问题讨论】:
-
不要造成更多混乱,我觉得 redux-saga 对你来说更优雅,以防你有多个同步或异步 axios 请求要处理。如果您有兴趣,我可以发布我们公司遵循的模式。
-
如果我知道你使用的模式,我会很感激你,但同时我希望这个项目使用 redux-thunk。这将是我们最后一次使用 redux-thunk。要继续这个项目,我必须坚持使用 thunk。你能帮我解决一下关于通用数据加载器的问题吗?
标签: javascript reactjs redux axios redux-thunk