React Native (二) Fetch实现网络连接

React Native (二) Fetch实现网络连接

一、Fetch API

fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点像jQuery ajax。但是,一定记住fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象

二、Using Fetch

2.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/await 语法处理异步

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

1729728-20190807225020177-823379974.jpg

以下是完整的代码,可以复制使用

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>
);

  }
}

效果图:
1729728-20190807224952328-1949911116.jpg

转载于:https://www.cnblogs.com/Crystal-Zh/p/11318407.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值