中止旧 API 获取请求 REACT

问题描述

在我的应用程序中, 有一个文本框,如果用户输入任何位置,则应用程序搜索该位置并以 5 秒的间隔创建 5 个 fetch API 请求

sed '$d'

我创建的内容如下,我在控制台中没有收到任何错误,但也无法中止旧请求

App.Current.Resources["IconColor"] = Color.Blue;

如何中止旧请求,每次生成新请求时

解决方法

有一个问题为什么它不起作用。您需要为向后端服务器创建的每个新请求创建 new AbortController

import AbortController from "abort-controller"

class ClassContainer extends React.Component {
    constructor(props) {
        super(props);
    }
    
    


//  Below is the function gets executed whenevr user enter any new location,show loading indictaor and creates 5 fetch API request
searchTravel=()=>{
 if (this.state.controller) {
       this.state.controller.abort();
 }
 
const controller = new AbortController();
const signal = controller.signal;

this.setState({
  controller: controller,signal: signal
})

 //show loader 
 //API hit to get new requestId
 this.getData(requestId)
}



//  This is a function which will create 5 fetch API request for every requestId==>
getData=(requestId)=>{
jsonBodyHotel : will have requestId & other stuff 

  const response = fetch("/API/GetResult" + "?rv=" + Math.random(),{
          method: "POST",body: jsonBodyHotel,headers: {
        "Content-type": "application/json; charset=UTF-8",},this.state.signal)
}