加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-native 网络请求,超时总结

发布时间:2020-12-15 07:19:27 所属栏目:百科 来源:网络整理
导读:react-native 网络请求总结 参考: [1] http://www.jb51.cc/article/p-qfauherj-rd.html [2] https://github.com/facebook/react-native/issues/2556 [3] https://github.com/robinpowered/react-native-fetch-polyfill react-native的网络请求,总会遇到这样

react-native 网络请求总结

参考:

[1] http://www.52php.cn/article/p-qfauherj-rd.html

[2] https://github.com/facebook/react-native/issues/2556

[3] https://github.com/robinpowered/react-native-fetch-polyfill

react-native的网络请求,总会遇到这样,或者那样的问题。这里我根据网上的资源,和自己的实践经验,总结下遇到的问题。

1. 使用哪种工具请求网络?

目前react-native推荐的是fetch,XHttpRequest等工具。我自己用的fetch方法。

2. 如何用fetch请求http?

http请求主流的分getpost方式. 都可以在 fetch方法中设置.

2.1 get方式请求

static get(url,callback) {
     fetch(url)
     .then((response) => response.text()) .then((responseText) => { callback(JSON.parse(responseText)); }).done(); }

代码中对返回的response对象,直接调用Json.parse()方法可以解析。也可以调用response.tojson()方法。

2.2 post请求

这里,我直接采用参考文章写的一个NetUtil.js工具类了,不过我们需要了解:请求时,我们可以设置响应的HTTP内容类型ContentType. 这个值,可以设置header的类型:application/json,application/x-www-form-urlencoded等(其实还有很多)。前者表示参数是json类型数据,后者表示参数是表单类型数据

'use strict';
import React,{
  Component,} from 'react-native';

class NetUitl extends React.Component {

  //post请求
  /** *url :请求地址 *data:参数 *callback:回调函数 */
  static  postForm(url,data,callback) {
     var fetchOptions = {
       method: 'POST',headers: {
         'Accept': 'application/json','Content-Type': 'application/x-www-form-urlencoded'
       },body:'data='+data+''//这里我参数只有一个data,大家可以还有更多的参数
     };

     fetch(url,fetchOptions)
     .then((response) => response.json())
     .then((responseData) => {
       // 这里responseData就是一个可以用的json对象了。
       callback(responseData); 
     }).catch(function(error) {?         callback(error,-1);
    }
}

/** *url :请求地址 *data:参数(Json对象) *callback:回调函数 */
static postJson (url,callback) {
    var fetchOptions = {
      method: 'POST',headers: {
        'Accept': 'application/json',//json形式
        'Content-Type': 'application/json'
      },body: JSON.stringify(data)
    };

  fetch(url,fetchOptions)
    .then((response) => response.json())
      .then((responseData) => {
        // 这里responseData就是一个可以用的json对象了。
        callback(responseData); 
      }).catch(function(error) {?        callback(error,-1);
     }
  }
}

module.exports = NetUitl;

3. 调用方式如下:

get的调用方法

NetUtil.get("http://v.juhe.cn/weather/index?format="+format+"&key="+key+"&cityname="+cityname,function (result) {
      // process result
   })

2.3 postJson的调用

let data={'username':'123','password':'123456','token':'HSHSIHIFAUINNSNAFKSKJFNKFKFNFNFNK'};
NetUitl.postJson(url,function (result){
    // process result a json object
  });

2.4 postForm的调用

let url = Global.LOGIN;
let formData = new FormData();?formData.append("id",id);?formData.append("username",username);
formData.put(" NetUitl.postForm(url,sx,function (result){ // process result });

超时怎么办?

目前也没有很好的办法解决超时,看网上很多方案都不可靠,主流的方式是抛弃这次http请求。用setTimeout() 方法,抛弃这次请求。我看到另外一种,引入一个[polyfill的文件]https://github.com/robinpowered/react-native-fetch-polyfill/blob/master/fetch-polyfill.js,然后在自己的网络请求方法里,采用它定义的fetch方法,就可以设置timeout参数。亲测有效。

这是我自己的HttpUtils.js 工具类:

HttpUtils.js

// 引入polyfill 解决不能设置超时的问题,直接把这个js文件拷到当前目录。
  // https://github.com/robinpowered/react-native-fetch-polyfill

  import fetch from './fetch-polyfill';

  console.warn("fetch url: " + url);
  getData(url,callback) {
?    fetch(url,{
          method: 'GET',headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
          },timeout: 20 * 1000
      })
      .then((response) => response.json()) .then((responseData) => { console.warn("response code:" + responseData.code) if(responseData.code === "C0000" || responseData.code === "1000" || responseData.code === 1000) { console.warn("response:" + responseData.data); callback(responseData.data,0); } else { callback(responseData,-1); } }).catch(error => { // an error when the request fails,such as during a timeout callback(null,-1); }); } } module.exports = { getData } 

使用方法:

let url = getUrls() + '&id=' + id;
?SelfHttp.getData(url,"",(data,code) => { ? console.warn("get data ....22222"); if(code === 0) { // 处理data对象,取决你返回的json格式 } else { // 显示错误界面 } }

希望对你的react-native之旅有帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读