axios请求取消场景及例子

本文介绍了如何在React应用中使用Axios发送网络请求,并提供两种场景的示例:在组件卸载时自动取消请求以及用户主动取消。同时强调了正确处理取消标记以避免内存泄漏和重复使用问题。
摘要由CSDN通过智能技术生成

背景

在前端开发中,网络请求是非常常见的操作。而有时候,我们可能需要在发送请求后取消它,比如用户在请求还未完成时离开了当前页面或者执行了其他操作,本文将介绍如何在使用 Axios 发送请求时取消这些请求。

基本概念

在 Axios 中,取消请求的基本思路是创建一个用于取消的标记(cancel token),并将其与特定请求关联。当需要取消请求时,我们可以使用这个标记通知 Axios 取消发送该请求。

案例一:在组件即将卸载时取消请求

在下面代码中,我们在组件的状态中设置了cancelToken和source,它们是Axios提供的用于创建CancelToken的工具。在fetchData函数中,我们通过将source.token作为配置参数传递给Axios请求,从而将请求与CancelToken关联。

当组件即将卸载(即componentWillUnmount生命周期方法被调用时),我们调用source.cancel方法来取消所有未完成的请求,并清理相关资源。通过在请求中捕获错误,我们可以判断是否请求被取消,并进行相应的处理。

import axios from 'axios';
 
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
      isLoading: false,
      cancelToken: axios.CancelToken,
      source: axios.CancelToken.source(),
    };
  }
 
  componentWillUnmount() {
    // 组件卸载前取消所有未完成的请求
    this.state.source.cancel('Operation canceled by the user.');
  }
 
  fetchData = () => {
    this.setState({ isLoading: true }, () => {
      axios.get('https://your-api.com/data', {
        cancelToken: this.state.source.token,
      })
      .then(response => {
        this.setState({ data: response.data, isLoading: false });
      })
      .catch(error => {
        if (axios.isCancel(error)) {
          console.log('Request canceled: ', error.message);
        } else {
          // Handle other errors
          this.setState({ isLoading: false });
        }
      });
    });
  };
 
  render() {
    const { data, isLoading } = this.state;
    return (
      <div>
        {isLoading ? <div>Loading...</div> : null}
        {data ? <div>{data}</div> : null}
        <button onClick={this.fetchData}>Fetch Data</button>
      </div>
    );
  }

案例二:用户主动取消请求

假设我们要在 React 中发送一个数据请求,用户在请求发出后点击了“取消”按钮。首先,我们需要创建一个可取消的 Axios 实例,并将其用于发送请求。

import React, { useState } from 'react';
import axios from 'axios';
 
function App() {
  const [data, setData] = useState('');
  const [request, setRequest] = useState(null);
 
  const fetchData = async () => {
    const source = axios.CancelToken.source();
    setRequest(source);
 
    try {
      const response = await axios.get('/api/data', {
        cancelToken: source.token
      });
      setData(response.data);
    } catch (error) {
      if (axios.isCancel(error)) {
        console.log('请求被取消', error.message);
      } else {
        console.log('请求出错', error.message);
      }
    }
  };
 
  const cancelRequest = () => {
    if (request) {
      request.cancel('手动取消请求');
    }
  };
 
  return (
    <div>
      <button onClick={fetchData}>发送请求</button>
      <button onClick={cancelRequest}>取消请求</button>
      <div>{data}</div>
    </div>
  );
}
 
export default App;

提示与注意事项

确保在组件卸载时取消请求,以免造成内存泄漏。
取消标记只能取消尚未完成的请求,无法取消已经完成的请求。
取消标记只能在特定的请求上使用一次,一旦使用过,就需要重新创建。

  • 15
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值