• react-native中的请求数据


    很多移动应用都需要从远程地址中获取数据或资源。你可能需要给某个 REST API 发起 POST 请求以提交用户数据,又或者可能仅仅需要从某个服务器上获取一些静态内容。
    使用 Fetch
    React Native 提供了和 web 标准一致的Fetch API,用于满足开发者访问网络的需求。
    发起请求
    要从任意地址获取内容的话,只需简单地将网址作为参数传递给 fetch 方法即可(fetch 这个词本身也就是获取的意思):
    fetch('https://mywebsite.com/mydata.json');
    Fetch 还有可选的第二个参数,可以用来定制 HTTP 请求一些参数。你可以指定 header 参数,
    或是指定使用 POST 方法,又或是提交数据等等:

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

    提交数据的格式关键取决于 headers 中的Content-Type。Content-Type有很多种,对应 body 的格式也有区别。到底应该采用什么样的Content-Type取决于服务器端,
    所以请和服务器端的开发人员沟通确定清楚。常用的'Content-Type'除了上面的'application/json',还有传统的网页表单形式,示例如下:

    
    fetch('https://mywebsite.com/endpoint/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: 'key1=value1&key2=value2',
    });
    

    注意:使用 Chrome 调试目前无法观测到 React Native 中的网络请求,你可以使用第三方的react-native-debugger来进行观测。
    我暂时还没有到使用react-native-debugger的时候,到了再写一篇关于这个使用的博客
    处理服务器的响应数据
    上面的例子演示了如何发起请求。很多情况下,你还需要处理服务器回复的数据。

    网络请求天然是一种异步操作(译注:同样的还有asyncstorage,请不要再问怎样把异步变成同步!无论在语法层面怎么折腾,
    、它们的异步本质是无法变更的。异步的意思是你应该趁这个时间去做点别的事情,比如显示 loading,而不是让界面卡住傻等)。
    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);
        });
    }
    

    你也可以在 React Native 应用中使用 ES2017 标准中的async/await 语法:

    // 注意这个方法前面有async关键字
    async function getMoviesFromApi() {
      try {
        // 注意这里的await语句,其所在的函数必须有async关键字声明
        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);
      }
    }
    

    别忘了 catch 住fetch可能抛出的异常,否则出错时你可能看不到任何提示。
    下面是使用fetch的一个小例子

    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>
            <FlatList
              data={this.state.dataSource}
              renderItem={({item}) => <Text>{item.title},{item.releaseYear}</Text>}
              keyExtractor={(item, index) => item.id}
            />
          </View>
          )
    
      }
    
    }
    

    我们在模拟器上面可以看到

    模拟器上的数据,返回的就是我们请求并展示的

    我们可以在浏览器看看到我们请求的数据类型

    使用其他的网络库
    React Native 中已经内置了XMLHttpRequest API(也就是俗称的 ajax)。一些基于 XMLHttpRequest 封装的第三方库也可以使用,
    例如frisbee或是axios等。但注意不能使用 jQuery,因为 jQuery 中还使用了很多浏览器中才有而 RN 中没有的东西(所以也不是所有 web 中的 ajax 库都可以直接使用)。

    var request = new XMLHttpRequest();
    request.onreadystatechange = (e) => {
      if (request.readyState !== 4) {
        return;
      }
    
      if (request.status === 200) {
        console.log('success', request.responseText);
      } else {
        console.warn('error');
      }
    };
    
    request.open('GET', 'https://mywebsite.com/endpoint/');
    request.send();
    

    需要注意的是,安全机制与网页环境有所不同:在应用中你可以访问任何网站,没有跨域的限制。
    WebSocket 支持
    React Native 还支持WebSocket,这种协议可以在单个 TCP 连接上提供全双工的通信信道。

    var ws = new WebSocket('ws://host.com/path');
    
    ws.onopen = () => {
      // connection opened
      ws.send('something'); // send a message
    };
    
    ws.onmessage = (e) => {
      // a message was received
      console.log(e.data);
    };
    
    ws.onerror = (e) => {
      // an error occurred
      console.log(e.message);
    };
    
    ws.onclose = (e) => {
      // connection closed
      console.log(e.code, e.reason);
    };
    
  • 相关阅读:
    批量修改文件的名字
    字节码指令以及操作数栈的分析
    字节码文件的分析
    类加载器详解
    类的加载-连接-初始化
    电商订单ElasticSearch同步解决方案--使用logstash
    springboot整合Mangodb实现crud,高级查询,分页,排序,简单聚合
    mongodb安装教程(亲测有效)
    Azure : 通过 SendGrid 发送邮件
    用java实现删除目录
  • 原文地址:https://www.cnblogs.com/smart-girl/p/10643454.html
Copyright © 2020-2023  润新知