React Native - 11 - 网络处理

许多移动应用程序需要从远程URL加载资源。您可能希望对REST API发出POST请求,或者您可能只需从另一台服务器获取一大块静态内容。

Using Fetch

React Native为您的网络需求提供了获取API。如果您以前使用过XMLHttpRequest或其他网络API,Fetch看起来会很熟悉。

发出请求

要从任意网址获取内容,只需传递网址即可获取:

fetch('https://mywebsite.com/mydata.json');

设置头参数,发送POST请求

fetch('[https://mywebsite.com/endpoint/](https://mywebsite.com/endpoint/)', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});

处理响应内容

网络是一种固有的异步操作。提取方法将返回一个Promise,使得直接编写以异步方式工作的代码:

function getMoviesFromApiAsync() {
  return fetch('[https://facebook.github.io/react-native/movies.json](https://facebook.github.io/react-native/movies.json)')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });
}

您也可以在React Native应用程序中使用建议的ES2017 async / await语法:

async function getMoviesFromApi() {
  try {
    let response = await fetch(
      '[https://facebook.github.io/react-native/movies.json](https://facebook.github.io/react-native/movies.json)'
    );
    let responseJson = await response.json();
    return responseJson.movies;
  } catch (error) {
    console.error(error);
  }
}

不要忘记抓取任何可能会被抛出的错误,否则会被默默地抛弃。

你可能感兴趣的:(React Native - 11 - 网络处理)