>我需要通过实时搜索 axios 请求取消以前的请求 - 我正在使用油门去反弹来发出请求,但是当现有单词被删除并更新新值时遇到问题 - 在某些情况下显示前一个单词的结果,我想我需要取消之前对同一请求 ID 的所有请求, 通读文章,但没有一篇适用于我的用例。感谢任何帮助,这里是我的代码。
还原剂:
switch (action.type) {
case GETTING_DATA:
return {
...state,
results: action.payload,
};
case SEARCH_DATA:
return {
...state,
Results: action.payload,
};
export function getSearch(value) {
return (dispatch) => {
dispatch({
type: GETTING_DATA,
});
const arg = {
search: value,
};
apiGet('abc', arg).then(response =>
getResults(dispatch, response));
};
}
const getResults = (dispatch, response) => {
dispatch({
type: SEARCH_DATA,
payload: response.data,
});
};
服务:
export const apiGet = async (path = '', args = {}) => {
const endpoint = "/aaa/aaa/aaa";
try {
return axios.get(endpoint, getConfig());
} catch (e) {
}
};
尝试以下操作:
将value
作为有效负载传递给GETTING_DATA
操作。这会将最新请求的值存储在状态中。
然后,在getResults
将相同的值与响应数据一起发送到化简器。在化简器内部,检查从 getResults
传递的值是否与通过 GETTING_DATA
存储在状态中的值相同。
如果是这样,则此数据是为了响应最新请求而来的,因此您希望将其存储在该状态中。否则,您可以忽略它。
换句话说:
行动:
switch (action.type) {
case GETTING_DATA:
return {
...state,
lastRequestTime: action.payload,
};
case SEARCH_DATA:
if (action.payload.lastRequestTime === state.lastRequestTime) {
return {
...state,
Results: action.payload.response,
};
} else {
return state
}
行动:
export function getSearch(value) {
return (dispatch) => {
const lastRequestTime = Date.now()
dispatch({
type: GETTING_DATA,
payload: lastRequestTime
});
const arg = {
search: value,
};
apiGet('abc', arg).then(response =>
getResults(dispatch, { response, lastRequestTime }));
};
}
const getResults = (dispatch, response) => {
dispatch({
type: SEARCH_DATA,
payload: response.data,
});
};
您可以创建这样一个小的帮助程序包装器,并在需要取消上一个请求的任何位置使用它:
// ../services.js
function createApi(baseURL) {
const axiosInst = axios.create({
baseURL,
});
// here you can set default headers:
axiosInst.defaults.headers.common['Content-Type'] = 'application/json';
// return the function with closure variable to use for canceling
return (type = 'get') => {
let call = null;
return (url, data, config) => {
if (call) {
call.cancel('Only one request allowed!');
}
call = axios.CancelToken.source();
const extConf = {
cancelToken: call.token,
...config,
};
switch (type) {
case 'request':
return api[type](extConf);
case 'get':
case 'delete':
case 'head':
return api[type](url, extConf);
default:
return api[type](url, data, extConf);
}
};
};
}
export const baseApi = createApi('http://localhost:5000/api/')
然后在像这样的地方使用它:
import baseApi from '../servises.js';
const fetchItemsService = baseApi('post');
//...
componentDidMount() {
fetchItemsService('/items').then(() => {});
}
//...