ReactNative之网络请求Fetch

不会说话就直接入题吧,在React中网络请求一般是使用Fecth函数,因为简单、方便、快捷,所以一下主要介绍Fecth的使用和封装逻辑。参考版本:"0.19.0"

  1. Fecth使用
fecth(url,{
method:'GET',
headers:{...}
})//请求URL、请求选项
.then(response => {//请求响应
  //do somthing
})
.catch(err => { //请求出错
  //do somthing
});
  1. Fecth封装过程
  • 定义
fetch = function(input, init) {  
var request  
if (Request.prototype.isPrototypeOf(input) && !init) {  
  request = input  
} else {   
 request = new Request(input, init) 
}
return new Promise(function(resolve, reject) { 
 var xhr = new XMLHttpRequest()
xhr.onload=...//监听请求状态变化
xhr.onerror =...//请求出错
xhr.open=...//打开请求,建立连接
xhr.send=...//发送请求数据
})
}
  • 由Fecth.js中的定义可以看出,Fecth传入Request对象或者URL+请求选项,最终返回Promise对象。

  • 请求返回的Promise实质是调用的XMLHttpRequest中的请求,这是Web中的异步请求对象,但是在Native中其实是不存在这个对象的,所以FB也封装 了一个XMLHttpRequest,当然这样也是为了统一。

  • 在ReactNative的lib包里的Network目录下,封装了XMLHttpRequest.android.js和XMLHttpRequest.ios.js

var RCTNetworking = require('RCTNetworking');//Native封装的Network类
var XMLHttpRequestBase = require('XMLHttpRequestBase');//ReactJS中的基类
class XMLHttpRequest extends XMLHttpRequestBase {
//...
var requestId = RCTNetworking.sendRequest(...);
this.didCreateRequest(requestId);
//...
}
  • 此处仅拿Android的RCTNetworking示例。
private final OkHttpClient mClient;
public final class NetworkingModule extends ReactContextBaseJavaModule {
  @Overridepublic 
String getName() {
  return "RCTNetworking";
}
/* package */ NetworkingModule(
ReactApplicationContext reactContext,    
@Nullable String defaultUserAgent,    
OkHttpClient client) { 
 super(reactContext); 
 mClient = client;  
//...
}
public NetworkingModule(final ReactApplicationContext context) {  
this(context, null, OkHttpClientProvider.getOkHttpClient());
}
@ReactMethod
/*** @param timeout value of 0 results in no timeout*/
public void sendRequest(
String method,    
String url,    
final int requestId,   
 ReadableArray headers,  
 ReadableMap data,    
final boolean useIncrementalUpdates,    
int timeout) {
//...
 mClient.newCall(requestBuilder.build()).enqueue(...);
//...
}
}
  • 可以看出,在Android的XMLHttpRequest 是依赖OKHttp实现的。OkHttpClientProvider只是对OkHttp进行了参数初始化
public class OkHttpClientProvider { 
private static @Nullable OkHttpClient sClient;  
public static OkHttpClient getOkHttpClient() {    
if (sClient == null) {     
 sClient = createClient();    
}    
return sClient;  
}  
private static OkHttpClient createClient() {    
OkHttpClient client = new OkHttpClient();    
// No timeouts by default   
 client.setConnectTimeout(0, TimeUnit.MILLISECONDS);    
client.setReadTimeout(0, TimeUnit.MILLISECONDS);    
client.setWriteTimeout(0, TimeUnit.MILLISECONDS);    
return client;  
}
}
  • 然后在MainReactPackage中注册。
@Overridepublic List createNativeModules(ReactApplicationContext reactContext) {  
return Arrays.asList(  
// ...
new NetworkingModule(reactContext),  
// ...
}
  • 最后是在ReactActivity中声明,在自己的Activity继承ReactActivity后实现。
//Returns a list of {@link ReactPackage} used by the app. 
//You'll most likely want to return at least the {@code MainReactPackage}. 
//If your app uses additional views or modules besides the default ones, 
//you'll want to include more packages here. 
protected abstract List getPackages();
@Override
protected List getPackages() {    
 return Arrays.asList(           
 new MainReactPackage());
}
  • 网络请求基本就是这样,有能力的应该可以替换成自己喜欢的网路库,不过OkHttp已经很优秀了。
ReactNative之网络请求Fetch_第1张图片
anjing

你可能感兴趣的:(ReactNative之网络请求Fetch)