React Native坑之(设置请求的连接超时时间)

本文介绍了在React Native中遇到无法设置fetch请求超时的问题,通过源码分析发现RN原生fetch并未提供timeout设置。作者通过追踪代码,发现在XMLHttpRequest中可以设置timeout,并给出了解决方案,最终实现通过自定义fetch封装来设定请求超时时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:好不容易rn算是入门了,可能是由于前面ios限制热更新的影响,导致大领导一句话:“防止后期可能存在的风险,所有rn项目不做啦!!“这尼玛就尴尬了~不过没关系,继续做我的原生android,当然,话虽如此,但是不代表我就此止步rn了,学习的脚步还是不能断哦,多一门技术还是没有什么坏处的。

好啦~废话不多说了,下面看看最近搞rn遇到的一点小烦恼~~~

因为项目中需要调一个接口,然后这个接口呢是有时间限制的,但是用rn原生的fetch去发送网络请求我压根就找不到有什么设置timeout的方法啊,这就尴尬了~~~~(难道rn连timeout这个东西都没有么?)带着疑问撸了一把源码,果然没有!!

我们在rn中用fetch发送一个请求可能是这样的:

async start(successCallBack, failCallBack) {
        try {
            let url = AppConst.BASE_URL + this.requestUrl();
            let response = await fetch(url, {
                headers: this.method == 'GET' ? null : this.headers,
                method: this.method,
                body: this.method == 'GET' ? null : this.body,
                timeout:10
            });
            let responseJson = await response.json();
            if(this.isShowing){
                this.dismissLoadingView();
            }
            if (responseJson&&!this.isCancled) {
                this.handleResponse(responseJson, successCallBack);
            } else {
                if (failCallBack&&!this.isCancled)failCallBack('请求失败');
            }
        } catch (erro) {
            console.log('catch-->'+erro);
            if(!this.isCancled)this.showSnackBar('网络异常'+erro);
            if (failCallBack&&!this.isCancled)failCallBack('网络异常');
            if(this.isShowing){
                this.dismissLoadingView();
            }
        }
    }

注意:这里的 timeout:10是我修改过后使用的,这个工具类的源码我待会会给出的。。

我们是直接调用fetch方法,然后传递两个参数,一个是url,一个是请求一些配置参数:

 let response = await fetch(url, {
                headers: this.method == 'GET' ? null : this.headers,
                method: this.method,
                body: this.method == 'GET' ? null : this.body,
                timeout:10
            });

然后我们点fetch方法进去看看它到底长啥样(它的位置在):

/xxx/node_modules/react-native/Libraries/Network/fetch.js
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule fetch
 * @nolint
 *
 */
'use strict';

import 'whatwg-fetch';

module.exports = {fetch, Headers, Request, Response};

好啦~~我们继续往下看看whatwg-fetch.js(它的代码太多,我就直接看重点fetch方法):

self.fetch = function(input, init) {
   
    return new Promise(function(resolve, reject) {
   
      var request = new Request(input, init)
      var xhr = new XMLHttpRequest()

      xhr.onload = function() {
   
        var options = {
          status: xhr.status,
          statusText: xhr.statusText,
          headers: parseHeaders(xhr.getAllResponseHeaders() || '')
        }
        options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get(
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值