React Native (二) Fetch實現網絡鏈接

React Native (二) Fetch實現網絡鏈接

1、Fetch API

fetch號稱是AJAX的替代品,是在ES6出現的,使用了ES6中的promise對象。Fetch是基於promise設計的。Fetch的代碼結構比起ajax簡單多了,參數有點像jQuery ajax。可是,必定記住fetch不是ajax的進一步封裝,而是原生js,沒有使用XMLHttpRequest對象react

2、Using Fetch

2.1 發送請求

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',
}),
});

2.2處理response

上面的例子展現瞭如何發出請求。在許多狀況下,須要處理從服務器返回的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>
);

  }
}

效果圖:
服務器

相關文章
相關標籤/搜索