前言:好不容易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(