React Native (二) Fetch实现网络连接
发布时间:2020-12-15 09:33:33 所属栏目:百科 来源:网络整理
导读:React Native (二) Fetch实现网络连接 一、Fetch API fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点像jQuery ajax。但是,一定记住 fetch不是ajax的进一步封装
React Native (二) Fetch实现网络连接一、Fetch APIfetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点像jQuery ajax。但是,一定记住fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。 二、Using Fetch2.1 发送请求fetch的用法是 fetch(url,{可选,可以放headers,method,body}); 我们这里用一个官方的API测试 fetch('https://facebook.github.io/react-native/movies.json') 这个API是get请求,可以不写后面的{},但是如果是post请求,可能需要写参数和method,以下面为例子 fetch('https://mywebsite.com/endpoint/',{ method: 'POST',headers: { Accept: 'application/json','Content-Type': 'application/json',},body: JSON.stringify({ firstParam: 'yourValue',secondParam: 'yourOtherValue',}),}); 2.2处理response上面的例子展示了如何发出请求。在许多情况下,需要处理从服务器返回的response, 网络本质上是一种异步操作。Fetch方法将返回一个Promise,使以异步方式编写代码变得简单 function getMoviesFromApiAsync() { return fetch('https://facebook.github.io/react-native/movies.json') .then((response) => response.json()) //注意这里不要写花括号,可能会报错 .then((responseJson) => { return responseJson.movies; }) .catch((error) => { console.error(error); }); } 你也可以使用再 ES2017 async function getMoviesFromApi() { try { let response = await fetch( 'https://facebook.github.io/react-native/movies.json',); let responseJson = await response.json(); return responseJson.movies; } catch (error) { console.error(error); } } 打印的返回的responce 以下是完整的代码,可以复制使用 import React from 'react'; import { FlatList,ActivityIndicator,Text,View } from 'react-native'; export default class FetchExample extends React.Component { constructor(props){ super(props); this.state ={ isLoading: true} } componentDidMount(){ return fetch('https://facebook.github.io/react-native/movies.json') .then((response) => response.json()) .then((responseJson) => { this.setState({ isLoading: false,dataSource: responseJson.movies,function(){ }); }) .catch((error) =>{ console.error(error); }); } render(){ if(this.state.isLoading){ return( <View style={{flex: 1,padding: 20}}> <ActivityIndicator/> </View> ) } return( <View style={{flex: 1,paddingTop:20}}> <FlatList data={this.state.dataSource} renderItem={({item}) => <Text>{item.title},{item.releaseYear}</Text>} keyExtractor={({id},index) => id} /> </View> ); } } 效果图: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |