android - 在 react-native 中取消获取请求

标签 android react-native fetch

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

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 函数,但它不起作用!!

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

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

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

请帮忙!

最佳答案

在 React Native 0.60 中不再需要任何 polyfill 来中止请求 changelog

这是来自 doc 的一个简单示例 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;

关于android - 在 react-native 中取消获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56120941/

相关文章:

php - 从数据库 php mysql 检索时图像显示空白

php - 如何在没有API的情况下从网站获取数据

android - 在 EditText 上调用 setText() 时到底发生了什么?

Android LinearLayout 填充宽度

reactjs - React Native 获取 View

react-native - 如何创建用户上次在线时间的 'last seen at' 时间?

javascript - 如何正确地将空映射设置为已解析的 json(这是一个新映射)?

java - 如何将 float 部分调整为下一个整数值

java - 从 URL 中删除特殊字符

react-native - 在React Native中添加metro.config.js后自定义字体出现问题