取消反应中的提取请求



是否有任何方法可以在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 })
          ....

请提供任何帮助!

您不再需要任何polyfill即可流产aect react Native 0.60 ChangElog

这是一个反应本的快速示例:

/**
 * 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;

我已经写了很多关于这个主题的文章。您还可以找到有关缺乏我在此处打开的React本地

中的apcontroller的第一个问题

降落在RN 0.60.0 中的支持,您可以在我的博客上找到有关此的文章,以及另一个将为您提供一个简单的代码,以使您开始提出可生存的请求(以及更多信息((也在反应本地。它还为非支持Envs(例如RN&lt; 0.60(实现了一些多填充。

您实际上可以通过安装此polyfill polortcontroller-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>
    )
  }
}

基本上在此示例中,单击" dostuff"按钮后,请求立即取消,并且您永远不会获得"完成"警报。可以肯定的是,它有效,尝试评论这些行,然后再次单击按钮:

alert('calling cancel');
this.controller.abort()

这次您将获得"完成"警报。

这是一个简单的示例,您可以使用React Native取消请求,请随时将其采用到您自己的用例中。

这是Snackexpo上的演示的链接

希望它有帮助:(

最好的解决方案是使用rxjs observables axios/fetch而不是承诺,请访问=>退订可观察的:

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

就是这样:(

最新更新