# React Native的HTTP请求

By [eth.mirror.xyz](https://paragraph.com/@eth-mirror-xyz) · 2021-10-19

---

前言
--

在一般的手机App中，HTTP请求是一种最常见的获取数据的方式。我们的App要连上广阔的互联网，才能带来一个丰富的世界。那么，在React Native中如何发起HTTP请求呢？

发起网络请求
------

要从任意地址获取内容的话，只需简单地将网址作为参数传递给fetch方法即可（fetch这个词本身也就是获取的意思）：

    fetch('https://mywebsite.com/mydata.json')
    

Fetch还有可选的第二个参数，可以用来定制HTTP请求一些参数。你可以指定header参数，或是指定使用POST方法，又或是提交数据等等，具体方法可以[参考文档](https://link.jianshu.com?t=http://reactnative.cn/docs/0.43/network.html#content)。

在这里，我们封装一个极简的get请求：

    var HttpClient={
        requestAsync:function(url , callback){
          fetch(url)
          .then((response) => response.json() )
          .then((responseJson)=>{
            callback.call(this,responseJson);
          })
          .catch((error)=>{
            console.error(error);
          });
        }
    
    }
    
    export default HttpClient;
    

这个方法非常简单，我们只设计了两个形参（url和回调）。整个fetch方法，十分类似函数式编程的模式。

一个例子
----

### 需求

请求`https://facebook.github.io/react-native/movies.json`获得它的title字段的信息并显示出来。

    import React, { Component } from 'react';
    import {
      AppRegistry,
      Text,
      View,
    
    } from 'react-native';
    
    import HttpClient from '../AwesomeProject/App/widget/HttpClient'
    
    class HelloWorld extends Component {
      render(){
        return (
          <Text>{this.state.title}</Text>
        )
      }
    
      constructor(props) {
        super(props);
        this.state={
          title:'loading',
        };
        var self = this;
        var httpUrl = 'https://facebook.github.io/react-native/movies.json';
        HttpClient.requestAsync(httpUrl , function(responseJson){
          self.setState({
            title:responseJson.title,
            movies:responseJson.movies,
          })
        });
      }
    }
    
    
    AppRegistry.registerComponent('AwesomeProject', () => HelloWorld);
    

这里我们运用了上一节的state的知识。在HelloWorld的初始化时，我们将`this.state.title`设为**loading**。然后在HTTP请求的回调中，将responseJson中的title取出，存入this.state.title中。

由于this.state的值发生改变，render方法会被重新调用。此时this.state.title中的值已经是我们请求回来的数据了，即可渲染成功。

---

*Originally published on [eth.mirror.xyz](https://paragraph.com/@eth-mirror-xyz/react-native-http)*
