# React Native的HTTP请求 **Published by:** [eth.mirror.xyz](https://paragraph.com/@eth-mirror-xyz/) **Published on:** 2021-10-19 **URL:** https://paragraph.com/@eth-mirror-xyz/react-native-http ## Content 前言在一般的手机App中,HTTP请求是一种最常见的获取数据的方式。我们的App要连上广阔的互联网,才能带来一个丰富的世界。那么,在React Native中如何发起HTTP请求呢?发起网络请求要从任意地址获取内容的话,只需简单地将网址作为参数传递给fetch方法即可(fetch这个词本身也就是获取的意思):fetch('https://mywebsite.com/mydata.json') Fetch还有可选的第二个参数,可以用来定制HTTP请求一些参数。你可以指定header参数,或是指定使用POST方法,又或是提交数据等等,具体方法可以参考文档。 在这里,我们封装一个极简的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中的值已经是我们请求回来的数据了,即可渲染成功。 ## Publication Information - [eth.mirror.xyz](https://paragraph.com/@eth-mirror-xyz/): Publication homepage - [All Posts](https://paragraph.com/@eth-mirror-xyz/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@eth-mirror-xyz): Subscribe to updates