使用 axios 取消卸载时的异步请求 [英] Cancel async request on unmount with axios

查看:33
本文介绍了使用 axios 取消卸载时的异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个带有 axios 插件的组件用于一些获取请求.我需要一些帮助才能在 react js 中的组件卸载事件上使用 axios 取消所有 xhr 请求.但是 axios 取消代码不起作用.它的 return me cancel() 不是函数错误.

代码示例:-

从'axios'导入axios;var CancelToken = axios.CancelToken;变量取消;axios.get('abc/xyz', {取消令牌:新的取消令牌(函数执行器(c){//一个执行器函数接收一个取消函数作为参数取消 = c;})});//取消请求取消();

请帮我在 axios 中实现取消请求.

谢谢.

解决方案

很简单.在 componentDidMount 中创建请求并在 componentWillUnmount 中取消它.将 url 替换为现有的 JSON 文件,此代码段将按预期工作:

class MyComponent extends Component {构造函数(道具){超级(道具)this.state = {数据: []}}组件DidMount(){this.axiosCancelSource = axios.CancelToken.source()公理.get('data.json', { cancelToken: this.axiosCancelSource.token }).then(响应 => {this.setState({数据: response.data.posts})}).catch(err => console.log(err))}组件将卸载(){this.axiosCancelSource.cancel('Axios 请求被取消.')}使成为 () {const { 数据 } = this.state返回 (<div>{data.items.map((item, i) => {返回 

{item.name}

})}

)}}

I have multiple component with axios plugin for some get requests. i need some help to cancel all xhr request with axios on component unmount event in react js. but the axios cancel code is not working. its return me cancel() is not a function error.

Code example:-

import axios from 'axios';


var CancelToken = axios.CancelToken;
var cancel;

axios.get('abc/xyz', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

Please help me to implement cancel request in axios.

Thanks.

解决方案

It is quite simple. Create the request in componentDidMount and cancel it in componentWillUnmount. Replace the url with an existing JSON file and this snippet will work as expected:

class MyComponent extends Component {
  constructor (props) {
    super(props)

    this.state = {
      data: []
    }
  }

  componentDidMount () {
    this.axiosCancelSource = axios.CancelToken.source()

    axios
      .get('data.json', { cancelToken: this.axiosCancelSource.token })
      .then(response => {
        this.setState({
          data: response.data.posts
        })
      })
      .catch(err => console.log(err))
  }

  componentWillUnmount () {
    this.axiosCancelSource.cancel('Axios request canceled.')
  }

  render () {
    const { data } = this.state

    return (
     <div>
          {data.items.map((item, i) => {
            return <div>{item.name}</div>
          })}
      </div>
    )
  }
}

这篇关于使用 axios 取消卸载时的异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆