Android 取消react native中的提取请求

Android 取消react native中的提取请求,android,react-native,fetch,Android,React Native,Fetch,有没有办法中止react本机应用程序上的获取请求 class MyComponent extends React.Component { state = { data: null }; componentDidMount = () => fetch('http://www.example.com') .then(data => this.setState({ data })) .catch(error => { thro

有没有办法中止react本机应用程序上的获取请求

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>;
}

请帮忙

您可以通过安装此polyfill来实现这一点 下面是一个取消请求的快速示例:

import React from 'react';
import { Button, View, Text } from 'react-native';
import 'abortcontroller-polyfill';

export default class HomeScreen extends React.Component {
  state = { todos: [] };

  controller = new AbortController();

  doStuff = () => {
    fetch('https://jsonplaceholder.typicode.com/todos',{
      signal: this.controller.signal
    })
    .then(res => res.json())
    .then(todos => {
      alert('done');
      this.setState({ todos })
    })
    .catch(e => alert(e.message));
    alert('calling cancel');
    this.controller.abort()
  }


  render(){
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Button title="Do stuff" onPress={() => { this.doStuff(); }} /> 
      </View>
    )
  }
}
这一次,您将收到“完成”警报

这是一个简单的hoe示例,您可以在react native中使用fetch取消请求,您可以在自己的用例中随意使用它

这里有一个链接到snackexpo的演示


希望有帮助:)

最好的解决方案是使用rxjs observable+axios/fetch,而不是promises,中止请求=>取消订阅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 0.60中中止请求不再需要任何多边形填充

下面是react native的一个快速示例:

/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow
*/

'use strict';

const React = require('react');
const {Alert, Button, View} = require('react-native');

class XHRExampleAbortController extends React.Component<{}, {}> {
  _timeout: any;

  _submit(abortDelay) {
    clearTimeout(this._timeout);
    // eslint-disable-next-line no-undef
    const abortController = new AbortController();
    fetch('https://facebook.github.io/react-native/', {
      signal: abortController.signal,
    })
      .then(res => res.text())
      .then(res => Alert.alert(res))
      .catch(err => Alert.alert(err.message));
    this._timeout = setTimeout(() => {
          abortController.abort();
    }, abortDelay);
  }

  componentWillUnmount() {
    clearTimeout(this._timeout);
  }

  render() {
    return (
      <View>
        <Button
          title="Abort before response"
          onPress={() => {
            this._submit(0);
          }}
        />
        <Button
          title="Abort after response"
          onPress={() => {
            this._submit(5000);
          }}
        />
      </View>
    );
  }
}

module.exports = XHRExampleAbortController;
/**
*版权所有(c)Facebook,Inc.及其附属公司。
*
*此源代码根据MIT许可证获得许可,该许可证位于
*此源目录树的根目录中的许可证文件。
*
*@格式
*@flow
*/
"严格使用",;
const React=require('React');
const{Alert,Button,View}=require('react-native');
类XHRExampleAbortController扩展了React.Component{
_超时:任意;
_提交(中止延迟){
clearTimeout(此.\u超时);
//eslint禁用下一行无未定义
const abortController=新的abortController();
取('https://facebook.github.io/react-native/', {
信号:abortController.signal,
})
。然后(res=>res.text())
。然后(res=>Alert.Alert(res))
.catch(err=>Alert.Alert(err.message));
这个。_timeout=setTimeout(()=>{
abortController.abort();
},abortDelay);
}
组件将卸载(){
clearTimeout(此.\u超时);
}
render(){
返回(
{
这是.\u提交(0);
}}
/>
{
本报告提交(5000);
}}
/>
);
}
}
module.exports=xhrexampleabort控制器;

关于这个主题,我实际上写了不少。 您还可以在我打开的React Native中找到关于旧的缺少中止控制器的第一个问题


支持登陆RN 0.60.0,您可以在我的博客上找到,并开始在React Native中提出可中止请求(以及更多)。它还为不支持的环境实现了一点polyfill(例如RN<0.60)。

这不起作用,我收到以下错误消息:可能未处理的承诺拒绝(id:0):[AbortError:Aborted]来自文档:-当请求中止时,此“polyfill”实际上不会关闭连接,但它将调用.catch()使用err.name=='abortorror'而不是.then(),这不会取消底层axios请求。只是结果的订阅。
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();
    }

}
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow
*/

'use strict';

const React = require('react');
const {Alert, Button, View} = require('react-native');

class XHRExampleAbortController extends React.Component<{}, {}> {
  _timeout: any;

  _submit(abortDelay) {
    clearTimeout(this._timeout);
    // eslint-disable-next-line no-undef
    const abortController = new AbortController();
    fetch('https://facebook.github.io/react-native/', {
      signal: abortController.signal,
    })
      .then(res => res.text())
      .then(res => Alert.alert(res))
      .catch(err => Alert.alert(err.message));
    this._timeout = setTimeout(() => {
          abortController.abort();
    }, abortDelay);
  }

  componentWillUnmount() {
    clearTimeout(this._timeout);
  }

  render() {
    return (
      <View>
        <Button
          title="Abort before response"
          onPress={() => {
            this._submit(0);
          }}
        />
        <Button
          title="Abort after response"
          onPress={() => {
            this._submit(5000);
          }}
        />
      </View>
    );
  }
}

module.exports = XHRExampleAbortController;