我正在制作一个实时搜索反应应用程序,您在输入中输入搜索词并得到结果(json),我尝试使用axios cancel token,但是它似乎不起作用,我不知道为什么。
class Search extends Component {
constructor(props) {
super(props);
this.state = {
query: '',
results: {},
isLoading: false,
message: ''
}
this.cancelPrevRequest = '';
}
fetchSearchResults = (query) => {
const jsonUrl = `https://jsonplaceholder.typicode.com/posts?q=${query}`;
if(this.cancelPrevRequest) {
this.cancelPrevRequest.cancel();
}
this.cancelPrevRequest = axios.CancelToken.source();
axios.get(jsonUrl, { cancelPrevRequest: this.cancelPrevRequest.token })
.then(res => {
const resNotFoundMsg = !res.data.length ? "Sorry, we couldn't find anything" : '';
this.setState({
results: res.data,
message: resNotFoundMsg,
isLoading: false
})
})
.catch(er => {
if(axios.isCancel(er) || er) {
this.setState({
isLoading: false,
message: "Error"
})
}
})
};
handleOnInputChange = (ev) => {
const query = ev.target.value;
this.setState({ query: query, isLoading: true, message: '' }, () => {
this.fetchSearchResults(query);
});
};
通常,由于我觉得更简单,因此"onChange"
我个人倾向于在调用API时使用这种方法debounce
。
至于为什么取消无效,您应该通过cancelToken
而不是cancelPrevRequest
。
确保阅读更多有关取消请求的信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句