javascript - 取消单独和所有 axios 请求

标签 javascript reactjs axios

问题:我有一个 React 应用程序,可以触发 axios 请求,您可以通过单击按钮来一一取消它们。现在,我又创建了一个按钮,该按钮应该立即取消所有请求,但我不知道该怎么做,因为我已经在单独取消的请求中配置了 cancelToken

问题:如何通过单击按钮取消我的代码示例中的所有三个请求?

代码示例:

组件包装器.jsx:

    const CancelToken = axios.CancelToken;

    <RequestComponent cancelToken={CancelToken}>
    <RequestComponent cancelToken={CancelToken}>
    <RequestComponent cancelToken={CancelToken}>

    <button onClick={/* Something here */}>Cancel all requests</button>

组件RequestComponent.jsx:

    let cancel;

    // new axios request
    axios.get('/user/12345', {
      cancelToken: new this.props.CancelToken(function executor(c) {
        cancel = c;
      })
    });

    // cancel this one particular request
    <button onClick={cancel('Request canceled')}>Cancel this one request</button>

我读到axios documentation ,但仍然无法弄清楚。

最佳答案

在保存 RequestComponents 的父组件中,传递一个将在请求后调用的附加属性。

<RequestComponent cancelToken={CancelToken} onRequest={persistCancel}>
<RequestComponent cancelToken={CancelToken} onRequest={persistCancel}>
<RequestComponent cancelToken={CancelToken} onRequest={persistCancel}>

当发出请求时,保留取消功能。

axios.get('/user/12345', {
  cancelToken: new this.props.CancelToken(function executor(c) {
    cancel = c;
    this.props.onRequest(c);
  })
});

在父组件中,存储取消函数

persistCancel = (cancel) => {
    this.setState({cancels: [...this.state.cancels, cancel]}
}

当您想要取消所有这些函数时,请调用这些函数。

<button onClick={()=>{this.state.cancels.forEach((c) => c())}}>Cancel all requests</button>

关于javascript - 取消单独和所有 axios 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57886274/

相关文章:

Javascript/JQuery 如何验证电话号码

javascript - 无法读取 ReactJS 中 null 的属性 'value'

javascript - 需要帮助理解为什么 javascript 对象属性未定义

mysql - ReactJS 与数据库的连接

javascript - 选中单选按钮时启用 HTML 选择,反之亦然

javascript - react 谷歌地图 API :Cannot read properties of undefined reading 'emit'

javascript - 迭代导入类的列表

reactjs - 如何使用 react redux 发出 post 请求?

javascript - 如何使用 Vue 和 Axios 获取 JSON 数据

javascript - FetchError : unable to verify the first certificate, 但我添加了rejectUnauthorized: false