【发布时间】:2017-09-08 04:52:34
【问题描述】:
我正在构建一个 react / redux webapp,我正在使用服务来进行所有 API 调用。每当 API 返回 401 - Unauthorized 时,我想向我的 redux 存储发送一个注销操作。
现在的问题是我的 api-service 没有反应组件,所以我无法获得对 dispatch 或 actions 的引用。
我首先做的是导出商店并手动调用dispatch,但正如我在这里读到的How to dispatch a Redux action with a timeout?,这似乎是一种不好的做法,因为它要求商店是单例的,这使得测试变得困难并且无法在服务器上渲染因为我们需要为每个用户提供不同的商店。
我已经在使用 react-thunk (https://github.com/gaearon/redux-thunk) 但我没有将t see how I can injectdispatch` 用于非反应组件。
我需要做什么?或者从反应组件外部调度动作通常是一种不好的做法?
这就是我的api.services.ts 现在的样子:
... other imports
// !!!!!-> I want to get rid of this import
import {store} from '../';
export const fetchWithAuth = (url: string, method: TMethod = 'GET', data: any = null): Promise<TResponseData> => {
let promise = new Promise((resolve, reject) => {
const headers = {
"Content-Type": "application/json",
"Authorization": getFromStorage('auth_token')
};
const options = {
body: data ? JSON.stringify(data) : null,
method,
headers
};
fetch(url, options).then((response) => {
const statusAsString = response.status.toString();
if (statusAsString.substr(0, 1) !== '2') {
if (statusAsString === '401') {
// !!!!!-> here I need to dispatch the logout action
store.dispatch(UserActions.logout());
}
reject();
} else {
saveToStorage('auth_token', response.headers.get('X-TOKEN'));
resolve({
data: response.body,
headers: response.headers
});
}
})
});
return promise;
};
谢谢!
【问题讨论】:
标签: reactjs asynchronous redux react-redux redux-thunk