mon*_*yjs 5 react-redux axios debounce
我需要使用实时搜索axios请求取消之前的请求 - 我正在使用限制 - 去抖来发出请求,但是当现有单词被删除并且新值被更新时我遇到了问题 - 在某些情况下,结果显示为前一个单词,我想我需要取消以前对同一个requestID的所有请求,阅读文章,但它们都不适用于我的用例.任何帮助,这是我的代码.
减速器:
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,
});
};
Run Code Online (Sandbox Code Playgroud)
服务:
export const apiGet = async (path = '', args = {}) => {
const endpoint = "/aaa/aaa/aaa";
try {
return axios.get(endpoint, getConfig());
} catch (e) {
}
};
Run Code Online (Sandbox Code Playgroud)
请尝试以下方法:
通过value作为有效载荷的GETTING_DATA动作.这将在状态中存储最新请求的值.
然后,getResults将相同的值与响应数据一起发送到reducer.在reducer中,检查传递的值是否与getResults存储在state via中的值相同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
}
Run Code Online (Sandbox Code Playgroud)
行动:
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,
});
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
949 次 |
| 最近记录: |