简体   繁体   English

如何通过令牌取消 axios 请求?

[英]How can I cancel axios request by token?

I'm trying to cancel axios request by token in useEffect:我正在尝试通过useEffect中的令牌取消axios请求:

(But Axios freezes after cancelation and doesn't work for another requests) [it's strange] (但 Axios 在取消后冻结,对其他请求不起作用)[奇怪]

// http-request.js

export const cancelelationSource = axios.CancelToken.source();

export const get = endpoint => {
  return axios.get(endpoint, {
    headers: { ...headers },
    timeout: 20000,
    cancelToken: cancelelationSource.token
  })
    .then(response => response.data)
    .catch(e => {
      console.log(e);
    });
}

then in component:然后在组件中:

import { get, cancelelationSource } from './http-request';

const About = () => {
  useEffect(() => {
    get('http://localhost:3001/test2').then(data => console.log(data))
  }, []);
  return (
    <h1>About</h1>
  )
}

const App = () => {
  useEffect(() => {
    get('http://localhost:3001/test').then(data => console.log(data))

    return () => cancelelationSource.cancel();
  }, []);

  return (
    <div>
      <Link to="/about">About</Link>
    </div>
  )
}

render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="/about" element={<About />} />
    </Routes>
  </BrowserRouter>,
  document.getElementById('root')
);

request cancelation works well when I click on the About link.当我单击“关于”链接时,请求取消效果很好。 but second API fetch doesn't work in component <About />但是第二个 API 提取在组件<About />中不起作用

I think axios cancels all requests... (Axios freezes for other requests) I want cancel previous requests but new request should be able to fetch data after change pages or redirect!我认为 axios 取消所有请求...(Axios 冻结其他请求)我想取消以前的请求,但新请求应该能够在更改页面或重定向后获取数据!

CancelToken and AbortController are one-shot things that cannot be reused after they are canceled. CancelToken 和 AbortController 是一次性的东西,取消后就不能重用了。 You must create a new token for the new query batch.您必须为新的查询批次创建一个新令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM