fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点像jQuery ajax。可是,必定记住fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。react
fetch的用法是git
fetch(url,{可选,能够放headers,method,body});
咱们这里用一个官方的API测试github
fetch('https://facebook.github.io/react-native/movies.json')
这个API是get请求,能够不写后面的{},可是若是是post请求,可能须要写参数和method,如下面为例子web
fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ firstParam: 'yourValue', secondParam: 'yourOtherValue', }), });
上面的例子展现了如何发出请求。在许多状况下,须要处理从服务器返回的response,ajax
网络本质上是一种异步操做。Fetch方法将返回一个Promise,使以异步方式编写代码变得简单json
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
/await
语法处理异步react-native
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); } }
打印的返回的responceapi
如下是完整的代码,能够复制使用promise
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> ); } }
效果图:
服务器