我是靠谱客的博主 畅快柜子,最近开发中收集的这篇文章主要介绍react取消所有请求_在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 = () =>

{this.state.data ? this.state.data : 'loading'}
;

}

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

....

Any help please !

解决方案

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

}

}

That is it :)

最后

以上就是畅快柜子为你收集整理的react取消所有请求_在react-native中取消获取请求的全部内容,希望文章能够帮你解决react取消所有请求_在react-native中取消获取请求所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(48)

评论列表共有 0 条评论

立即
投稿
返回
顶部