ReactNative: 数据请求

一、简介

数据,任何一款产品必不可少的核心,没有数据,一切就毫无根据可言。在开发中,数据基本上都需要从服务器去获取。ReactNative本身实现了网络API功能,它遵循浏览器的实现方式,也即XMLHTTPRequest API。参与前端开发的工程师,对XMLHTTPRequest应该非常了解,XMLHTTPRequest在Web中存在跨域问题,但在ReactNative中则不存在。当然也可以使用jquery中的Ajax库进行网络数据请求,Ajax的本质其实还是使用了XMLHttpRequest。 在ReactNative中,除了可以使用XMLHTTPRequest外,Fetch这个API的使用更是非常广泛,Fetch是一个高度封装的网络API,拥有函数式编程的特点,ReactNative默认已经实现了Fetch。

 

二、XMLHTTPRequest

//初始化对象
const request = new XMLHttpRequest();

//请求过程
request.onreadystatechange = (e) => {
   //0:未初始化 1:载入 2:载入完成 3:交互 4:完成
   if (request.readyState !== 4){
       return;
   }
   if (request.status === 200){
       console.log("success: ", request.responseText);
   } else {
       console.warn("error");
   }
};

//请求开始
const url = "https://randomuser.me/api?results=10";
request.open('GET', url);
request.send();

 

三、Fetch

//发起请求
const url = "https://randomuser.me/api?results=10";
fetch(url)
.then((data) => {
      return data.text();
})
.then((response) => {
      console.log("success: ", response);
})
.catch((error) => {
      console.warn("error: "+error);
})

 

四、封装Fetch

//封装的POST请求,GET/PUT/DELETE等请求类似
POST(url, parameter, success, failure) {

     //封装请求配置: 请求方法、请求头、请求体
     let opt = {
          method: 'POST',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
          },
          body: JSON.stringify(parameter)
      };
      //发起请求
      fetch(url, opt)
      .then((data) => data.text())
      .then((response) => { success(response) } )
      .catch((error) => { failure(error) } )
}

  

五、测试

代码如下:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    TouchableHighlight,
    View
} from 'react-native';

export default class App extends Component {

    //事件
    _event1(){
        //初始化对象
        const request = new XMLHttpRequest();

        //请求过程
        request.onreadystatechange = (e) => {
            //0:未初始化 1:载入 2:载入完成 3:交互 4:完成
            if (request.readyState !== 4){
                return;
            }
            if (request.status === 200){
                console.log("success: ", request.responseText);
            } else {
                console.warn("error");
            }
        };

        //请求开始
        const url = "https://randomuser.me/api?results=10";
        request.open('GET', url);
        request.send();
    }

    _event2(){

        //发起请求
        const url = "https://randomuser.me/api?results=10";
        fetch(url)
            .then((data) => {
                return data.text();
            })
            .then((response) => {
                console.log("success: ", response);
            })
            .catch((error) => {
                console.warn("error: "+error);
            })
    }

    _event3(){

        //发送POST请求
        const url = "https://randomuser.me/api";
        this._POST(url,{results:10}, (response) => {
            console.log("success: ", response);
        }, (error) => {
            console.warn("error: "+error);
        });
    }


    //封装的POST请求,GET/PUT/DELETE等请求类似
    _POST(url, parameter, success, failure) {

        //封装请求配置: 请求方法、请求头、请求体
        let opt = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(parameter)
        };
        //发起请求
        fetch(url, opt)
            .then((data) => data.text())
            .then((response) => { success(response) } )
            .catch((error) => { failure(error) } )
    }

    render() {
        return (
            <View style={styles.container}>
                <TouchableHighlight onPress={this._event1.bind(this)}>
                    <Text style={{color:'red', fontSize:25}}>XMLHttpRequest请求</Text>
                </TouchableHighlight>
                <TouchableHighlight onPress={this._event2.bind(this)}>
                    <Text style={{color:'red', marginTop: 30, fontSize:25}}>Fetch请求</Text>
                </TouchableHighlight>
                <TouchableHighlight onPress={this._event3.bind(this)}>
                    <Text style={{color:'red', marginTop: 30, fontSize:25}}>封装Fetch: POST</Text>
                </TouchableHighlight>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

AppRegistry.registerComponent('App', () => App);

打印如下:

{
    "results": [
        {
            "gender": "female",
            "name": {
                "title": "Ms",
                "first": "Sara",
                "last": "Mendez"
            },
            "location": {
                "street": {
                    "number": 874,
                    "name": "Calle Mota"
                },
                "city": "Murcia",
                "state": "Comunidad Valenciana",
                "country": "Spain",
                "postcode": 27841,
                "coordinates": {
                    "latitude": "-18.6260",
                    "longitude": "111.3075"
                },
                "timezone": {
                    "offset": "+5:30",
                    "description": "Bombay, Calcutta, Madras, New Delhi"
                }
            },
            "email": "sara.mendez@example.com",
            "login": {
                "uuid": "d8bb1d88-31c2-49f0-8c39-a97e29fbccd8",
                "username": "organicmouse620",
                "password": "carpedie",
                "salt": "eWjJ0bVY",
                "md5": "235da64599d1177e3998dc9566be97c8",
                "sha1": "aef5d5471f1d1d880bec926c111ab2bd683c7103",
                "sha256": "38b48b23a0baab901b5191da6e366178f35b87a2d46fb2375d4faffab3b05006"
            },
            "dob": {
                "date": "1971-01-25T14:40:39.658Z",
                "age": 49
            },
            "registered": {
                "date": "2018-03-14T04:25:24.405Z",
                "age": 2
            },
            "phone": "959-777-856",
            "cell": "695-560-245",
            "id": {
                "name": "DNI",
                "value": "34734851-Y"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/16.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/16.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/16.jpg"
            },
            "nat": "ES"
        },
        {
            "gender": "female",
            "name": {
                "title": "Miss",
                "first": "Juliette",
                "last": "Anderson"
            },
            "location": {
                "street": {
                    "number": 7537,
                    "name": "Grand Ave"
                },
                "city": "Killarney",
                "state": "New Brunswick",
                "country": "Canada",
                "postcode": "D4K 9F7",
                "coordinates": {
                    "latitude": "33.6344",
                    "longitude": "157.7765"
                },
                "timezone": {
                    "offset": "+5:45",
                    "description": "Kathmandu"
                }
            },
            "email": "juliette.anderson@example.com",
            "login": {
                "uuid": "89a04785-7c67-4e92-b289-02cc874bfcd4",
                "username": "lazybutterfly717",
                "password": "jennie",
                "salt": "7VYtsFzr",
                "md5": "3290c01ebcc8458d9631d158ed4a623e",
                "sha1": "a90080d2b0639dea297407cd82cf7d1675408898",
                "sha256": "caa0e0fe10cc6e8c42faf4bd563504e0a4c49f4db85a55e09a762fbf2c53d874"
            },
            "dob": {
                "date": "1953-06-24T10:50:48.743Z",
                "age": 67
            },
            "registered": {
                "date": "2007-06-22T22:45:16.422Z",
                "age": 13
            },
            "phone": "878-246-0336",
            "cell": "522-441-9154",
            "id": {
                "name": "",
                "value": null
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/13.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/13.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/13.jpg"
            },
            "nat": "CA"
        },
        {
            "gender": "male",
            "name": {
                "title": "Mr",
                "first": "Konsta",
                "last": "Lammi"
            },
            "location": {
                "street": {
                    "number": 6810,
                    "name": "Itsenäisyydenkatu"
                },
                "city": "Punkalaidun",
                "state": "Kainuu",
                "country": "Finland",
                "postcode": 72044,
                "coordinates": {
                    "latitude": "-37.1572",
                    "longitude": "5.0063"
                },
                "timezone": {
                    "offset": "+7:00",
                    "description": "Bangkok, Hanoi, Jakarta"
                }
            },
            "email": "konsta.lammi@example.com",
            "login": {
                "uuid": "64781a24-2dcc-4379-856a-834771e29727",
                "username": "organicrabbit796",
                "password": "time",
                "salt": "m1PFEtjt",
                "md5": "614962daa63ec13fe9c4bb15e178372c",
                "sha1": "a272a8e48f8d093ef64955b51628162144dad4bf",
                "sha256": "fb69a980b2e3ecfc80fe0c4bd7e6936f5f2801082abdcd970e5833c92675d54a"
            },
            "dob": {
                "date": "1988-10-11T04:58:50.786Z",
                "age": 32
            },
            "registered": {
                "date": "2011-07-09T02:21:08.490Z",
                "age": 9
            },
            "phone": "03-996-326",
            "cell": "047-498-63-89",
            "id": {
                "name": "HETU",
                "value": "NaNNA611undefined"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/men/43.jpg",
                "medium": "https://randomuser.me/api/portraits/med/men/43.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/men/43.jpg"
            },
            "nat": "FI"
        },
        {
            "gender": "female",
            "name": {
                "title": "Miss",
                "first": "June",
                "last": "Hernandez"
            },
            "location": {
                "street": {
                    "number": 2254,
                    "name": "Green Rd"
                },
                "city": "Hervey Bay",
                "state": "Queensland",
                "country": "Australia",
                "postcode": 998,
                "coordinates": {
                    "latitude": "-17.7075",
                    "longitude": "153.9846"
                },
                "timezone": {
                    "offset": "+9:30",
                    "description": "Adelaide, Darwin"
                }
            },
            "email": "june.hernandez@example.com",
            "login": {
                "uuid": "3b6577ca-4a3b-43da-8752-5e9ccd862fe9",
                "username": "bigbird555",
                "password": "chad",
                "salt": "F3nvNJqs",
                "md5": "32dc11847b941272f8ea76a219a50d6f",
                "sha1": "14edd4e0bc643180b5ac7f72c3dca31dac859764",
                "sha256": "c02b77c9014e562bcce4b1c7e5b139e5049059421a908e0d9be13aba30d484ee"
            },
            "dob": {
                "date": "1973-11-19T14:43:15.073Z",
                "age": 47
            },
            "registered": {
                "date": "2011-04-15T11:20:17.477Z",
                "age": 9
            },
            "phone": "08-7210-2716",
            "cell": "0400-007-818",
            "id": {
                "name": "TFN",
                "value": "039448965"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/8.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/8.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/8.jpg"
            },
            "nat": "AU"
        },
        {
            "gender": "female",
            "name": {
                "title": "Mrs",
                "first": "Madison",
                "last": "Ambrose"
            },
            "location": {
                "street": {
                    "number": 4954,
                    "name": "Grand Ave"
                },
                "city": "St. George",
                "state": "Newfoundland and Labrador",
                "country": "Canada",
                "postcode": "T6N 1O3",
                "coordinates": {
                    "latitude": "-34.0240",
                    "longitude": "-95.9018"
                },
                "timezone": {
                    "offset": "+6:00",
                    "description": "Almaty, Dhaka, Colombo"
                }
            },
            "email": "madison.ambrose@example.com",
            "login": {
                "uuid": "ab7fcb5e-ea12-40f8-a3e3-57758e35a944",
                "username": "sadwolf487",
                "password": "jayjay",
                "salt": "1SYzzWf4",
                "md5": "e70027ca7d924acbc001c740b2b18087",
                "sha1": "4c31e2f296563f865f5b2f2c82476c8288cd58f7",
                "sha256": "6aa9b7ff174753baa0c6ceaac6137a13db428bafe32049a8378755ddf4f207a2"
            },
            "dob": {
                "date": "1966-08-14T23:33:54.811Z",
                "age": 54
            },
            "registered": {
                "date": "2014-02-18T11:26:32.803Z",
                "age": 6
            },
            "phone": "976-605-3846",
            "cell": "966-570-0762",
            "id": {
                "name": "",
                "value": null
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/31.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/31.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/31.jpg"
            },
            "nat": "CA"
        },
        {
            "gender": "male",
            "name": {
                "title": "Mr",
                "first": "Aubin",
                "last": "Brun"
            },
            "location": {
                "street": {
                    "number": 352,
                    "name": "Rue de L'Église"
                },
                "city": "Colombes",
                "state": "Marne",
                "country": "France",
                "postcode": 49432,
                "coordinates": {
                    "latitude": "-51.7177",
                    "longitude": "-140.3285"
                },
                "timezone": {
                    "offset": "+4:00",
                    "description": "Abu Dhabi, Muscat, Baku, Tbilisi"
                }
            },
            "email": "aubin.brun@example.com",
            "login": {
                "uuid": "08881dc3-203c-41a1-801c-d1e04f67cfb8",
                "username": "ticklishmeercat430",
                "password": "49ers",
                "salt": "3ksfxJc2",
                "md5": "c02c7542bdca832cdc1fe95a46fdb655",
                "sha1": "0791541b577ecf6edd9cc8ae81de61fac40359aa",
                "sha256": "901ba499d96340337843758089006ef5218859a1aef9c2a0f34e037d7593ea79"
            },
            "dob": {
                "date": "1960-02-20T19:08:01.553Z",
                "age": 60
            },
            "registered": {
                "date": "2013-05-12T03:44:25.127Z",
                "age": 7
            },
            "phone": "02-93-87-82-59",
            "cell": "06-30-89-24-57",
            "id": {
                "name": "INSEE",
                "value": "1NNaN50786732 54"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/men/72.jpg",
                "medium": "https://randomuser.me/api/portraits/med/men/72.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/men/72.jpg"
            },
            "nat": "FR"
        },
        {
            "gender": "female",
            "name": {
                "title": "Mrs",
                "first": "Aubrey",
                "last": "Ma"
            },
            "location": {
                "street": {
                    "number": 8258,
                    "name": "Alfred St"
                },
                "city": "Chesterville",
                "state": "British Columbia",
                "country": "Canada",
                "postcode": "S8V 4F9",
                "coordinates": {
                    "latitude": "-75.3265",
                    "longitude": "-136.3247"
                },
                "timezone": {
                    "offset": "-3:30",
                    "description": "Newfoundland"
                }
            },
            "email": "aubrey.ma@example.com",
            "login": {
                "uuid": "fb06c78d-57db-4d66-81e7-bf66a5ec9a08",
                "username": "goldenswan659",
                "password": "buddie",
                "salt": "15Io1fGG",
                "md5": "8e14dc06e28ff3b31abd934097c8f2a2",
                "sha1": "e20cb3d3aede72c9aeba0357c4c93725db574b10",
                "sha256": "75f0b1b6731a95a80696f0b40de8d0d63254a00f3c115f87ccefef4f88f6089a"
            },
            "dob": {
                "date": "1951-05-28T03:46:26.578Z",
                "age": 69
            },
            "registered": {
                "date": "2019-02-03T12:57:48.787Z",
                "age": 1
            },
            "phone": "585-993-8292",
            "cell": "150-161-2575",
            "id": {
                "name": "",
                "value": null
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/60.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/60.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/60.jpg"
            },
            "nat": "CA"
        },
        {
            "gender": "male",
            "name": {
                "title": "Mr",
                "first": "Eliot",
                "last": "Le Gall"
            },
            "location": {
                "street": {
                    "number": 34,
                    "name": "Rue des Ecrivains"
                },
                "city": "Nanterre",
                "state": "Tarn-et-Garonne",
                "country": "France",
                "postcode": 30270,
                "coordinates": {
                    "latitude": "-34.2439",
                    "longitude": "122.0541"
                },
                "timezone": {
                    "offset": "-7:00",
                    "description": "Mountain Time (US & Canada)"
                }
            },
            "email": "eliot.legall@example.com",
            "login": {
                "uuid": "79faa8c0-1b94-4ba8-9857-4119094a7e24",
                "username": "goldenduck460",
                "password": "piano",
                "salt": "VWz0KT06",
                "md5": "d48883294c45b79bc4535437e5d3ff92",
                "sha1": "0fd8195c018372ca00dc52586f04c464778c43f3",
                "sha256": "351f434b05ab61bb60b522fb2a6de98b541dba6b8aa32a73e89bb5ffa27ca3ac"
            },
            "dob": {
                "date": "1964-07-01T09:08:46.658Z",
                "age": 56
            },
            "registered": {
                "date": "2009-10-11T17:52:32.300Z",
                "age": 11
            },
            "phone": "02-02-63-46-13",
            "cell": "06-03-30-24-41",
            "id": {
                "name": "INSEE",
                "value": "1NNaN85692617 93"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/men/42.jpg",
                "medium": "https://randomuser.me/api/portraits/med/men/42.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/men/42.jpg"
            },
            "nat": "FR"
        },
        {
            "gender": "male",
            "name": {
                "title": "Mr",
                "first": "Nathan",
                "last": "Cole"
            },
            "location": {
                "street": {
                    "number": 8559,
                    "name": "Main Street"
                },
                "city": "Sheffield",
                "state": "County Down",
                "country": "United Kingdom",
                "postcode": "SX31 3TW",
                "coordinates": {
                    "latitude": "-74.8588",
                    "longitude": "-43.3099"
                },
                "timezone": {
                    "offset": "+4:30",
                    "description": "Kabul"
                }
            },
            "email": "nathan.cole@example.com",
            "login": {
                "uuid": "90d0d954-ab3e-45eb-948e-60cf368b91ce",
                "username": "tinymouse675",
                "password": "ibanez",
                "salt": "34BJ2b38",
                "md5": "f1badbe6b7d0e221383e7ec08ed2496d",
                "sha1": "ebb8a3a0c841a70ddc910777180a408ef3564d4a",
                "sha256": "66337b7257acfc6abe70d7ac0f96a9eff3c5c7ec560188ed43e75b02d4cd511f"
            },
            "dob": {
                "date": "1984-09-04T09:19:18.775Z",
                "age": 36
            },
            "registered": {
                "date": "2010-08-27T15:18:46.741Z",
                "age": 10
            },
            "phone": "015394 65604",
            "cell": "0752-233-587",
            "id": {
                "name": "NINO",
                "value": "XB 34 08 00 G"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/men/73.jpg",
                "medium": "https://randomuser.me/api/portraits/med/men/73.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/men/73.jpg"
            },
            "nat": "GB"
        },
        {
            "gender": "female",
            "name": {
                "title": "Ms",
                "first": "Pilar",
                "last": "Gallardo"
            },
            "location": {
                "street": {
                    "number": 6962,
                    "name": "Calle Covadonga"
                },
                "city": "Cuenca",
                "state": "Cataluña",
                "country": "Spain",
                "postcode": 40516,
                "coordinates": {
                    "latitude": "35.3169",
                    "longitude": "94.3808"
                },
                "timezone": {
                    "offset": "-11:00",
                    "description": "Midway Island, Samoa"
                }
            },
            "email": "pilar.gallardo@example.com",
            "login": {
                "uuid": "53992a29-94d1-4219-9e83-d18825d91f98",
                "username": "goldenbear546",
                "password": "simple1",
                "salt": "e0OYmq1N",
                "md5": "87799cb34e5586cc536289e702b33c0e",
                "sha1": "59649c9546c87596e8be42168a27b22d99b62d21",
                "sha256": "46785dfffdcea07e57d912522488d1e8eb6978be3cbdd9cb352a41eb2da8fd7c"
            },
            "dob": {
                "date": "1978-09-02T20:13:25.149Z",
                "age": 42
            },
            "registered": {
                "date": "2019-01-11T05:21:07.954Z",
                "age": 1
            },
            "phone": "956-303-638",
            "cell": "692-711-383",
            "id": {
                "name": "DNI",
                "value": "68641455-W"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/49.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/49.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/49.jpg"
            },
            "nat": "ES"
        }
    ],
    "info": {
        "seed": "bbd92f2653c51a4c",
        "results": 10,
        "page": 1,
        "version": "1.3"
    }
}
View Code

截图如下:

posted @ 2020-01-15 18:14  XYQ全哥  阅读(432)  评论(0编辑  收藏  举报