React JS中是否有一种方法可以阻止请求(如果正在执行的话),我在谈论同一请求。
编辑: 这是我的代码:
const fetching = false;
export default (type, filter, dateFilter, position) => {
if(fetching) return Promise.reject(new Error('Request in progress'));
fetching = true;
return fetch(URL + `/search/${type}/${filter}/${dateFilter}/${position}/0/0`)
.then(response => Promise.all([response, response.json()]))
//!!! My problem is that now i cannot put .then(() => fetching = false))
// here.If i put it i get undefined in my then(res) of my getDataApi
// so i cannot make requests again because fetching stays in true.
}
为了更好地理解,这是我的控制台,{:{3}}
.then(() => {
fetching = false;
console.log("fetching", fetching)
})
actions.js
export const fetchData = (type, filter, dateFilter, position) => {
return (dispatch, getState) => {
const state = getState();
dispatch(getData())
getDataApi(type, filter, dateFilter, position)
.then(res => {
console.log("RES", res)
if (res !== undefined) {
console.log("entro")
//here it doesnt enter if i put fething false above
// is like somehow the promise.all is not resolved if i
// put it above or under the then with the fetching =
// false but i need it, what can i do?
if (state.dataReducer.data.length === 0) {
dispatch(getDataSuccess(res[1]))
} else {
dispatch(getDataSuccess(res[1], state.dataReducer.data))
}
}
})
.catch((err) => console.log(9999, err))
}
}
答案 0 :(得分:1)
不确定您是否真的需要对此进行复杂化处理,请保留一些状态,以指示您的请求已在进行中,因此可以忽略后续请求。
您没有提到如何管理应用程序状态,因此这是一个基于您的代码的非常简单的示例
let fetching = false;
export default (type, filter, dateFilter, position) => {
if (fetching) return Promise.resolve();
fetching = true;
return fetch('...')
.then(response => {
// handle response
})
.catch(e => {
// handle error
})
.then(() => {
fetching = false; // reset state
});
}
答案 1 :(得分:-1)
我解决了。这是我的代码:
return fetch(URL + `/search/${type}/${filter}/${dateFilter}/${position}/0/0`)
.then(response => Promise.all([response, response.json()]))
.then(([response, responseObj]) => {
fetching = false;
return [response, responseObj];
})
.catch(err => {
fetching = false;
return Promise.reject(err); // If you want to handle the error in a chained .catch()
})