Javascript Redux thunk和axios-请求取消
我有一个带有redux thunk、redux pack和axios的应用程序 我的行动如下:Javascript Redux thunk和axios-请求取消,javascript,reactjs,redux,axios,redux-thunk,Javascript,Reactjs,Redux,Axios,Redux Thunk,我有一个带有redux thunk、redux pack和axios的应用程序 我的行动如下: export const getEntities = () => (dispatch, getState, { api }) => { return dispatch({ type: ENTITIES_LOAD, promise: api.getEntities(), meta: {}, }); }; const cancelRequest = (keyN
export const getEntities = () => (dispatch, getState, { api }) => {
return dispatch({
type: ENTITIES_LOAD,
promise: api.getEntities(),
meta: {},
});
};
const cancelRequest = (keyName) => {
if (typeof window === 'undefined') return;
const cancelMethod = window.cancellationTokens[keyName];
if (!cancelMethod) return;
cancelMethod();
}
我把它们称为componentDidMount
我的问题是-取消这些操作以及请求本身的最佳方式是什么?我已经读过axios使用的Cancel令牌,但是我应该如何首先取消操作?我发现自己正在使用Cancel令牌取消请求。这是解决这个问题的一种方法,但是我将它们附加到了一个全局变量,比如window,所以每次发出请求时,新的令牌都会用它自己的密钥添加到一个对象中,每次请求完成时,这个密钥都会被移除 因此,我在应用程序的客户端部分提供了类似的功能:
window.cancellationTokens = { myOwnTokenKey: theActualToken }
如果需要取消请求,例如用户离开在componentDidMount上获取数据的路由,我只需执行以下操作:
cancelRequest(nameOfTheKey);
名为cancelRequest的函数接受一个参数,即请求的实际键,如下所示:
export const getEntities = () => (dispatch, getState, { api }) => {
return dispatch({
type: ENTITIES_LOAD,
promise: api.getEntities(),
meta: {},
});
};
const cancelRequest = (keyName) => {
if (typeof window === 'undefined') return;
const cancelMethod = window.cancellationTokens[keyName];
if (!cancelMethod) return;
cancelMethod();
}
也许你应该考虑加入复仇传奇,让行动取消很容易。
参见文档默认情况下,这基本上是不可能的。看看RxJS。