在react-native中取消获取请求 [英] Cancel a fetch request in react-native

查看:261
本文介绍了在react-native中取消获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以中止react-native应用程序上的提取请求吗?

Is there any way to abort a fetch request on react-native app ?

class MyComponent extends React.Component {
  state = { data: null };

  componentDidMount = () =>
    fetch('http://www.example.com')
      .then(data => this.setState({ data }))
      .catch(error => {
        throw error; 
      });

  cancelRequest = () => {
   //???
  };

  render = () => <div>{this.state.data ? this.state.data : 'loading'}</div>;
}

我尝试了AbortController类中的abort函数,但是它不起作用!

i tried the abort function from AbortController class but it's not working !!

...
abortController = new window.AbortController();

cancelRequest =  () => this.abortController.abort();

componentDidMount = () =>
        fetch('http://www.example.com', { signal: this.abortController.signal })
          ....

请帮助!

推荐答案

最好的解决方案是使用rxjs observables + axios/fetch而不是promises,中止请求=>取消订阅可观察项:

the best solution is using rxjs observables + axios/fetch instead of promises, abort a request => unsubscribe an observable :

import Axios from "axios";
import {
    Observable
} from "rxjs";

export default class HomeScreen extends React.Component {
    subs = null;

    doStuff = () => {
        let observable$ = Observable.create(observer => {
            Axios.get('https://jsonplaceholder.typicode.com/todos', {}, {})
                .then(response => {
                    observer.next(response.data);
                    observer.complete();
                })
        });

        this.subs = observable$.subscribe({
            next: data => console.log('[data] => ', data),
            complete: data => console.log('[complete]'),
        });

    }

    cancel = () =>
        if (this.subs) this.subs.unsubscribe()

    componentWillUnmount() {
        if (this.subs) this.subs.unsubscribe();
    }

}

就是这样:)

这篇关于在react-native中取消获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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