React Native 上手 - 7.网络

React Native

上一篇:React Native 上手 - 6.ListView

大部分 App 都离不开网络资源请求。React Native 提供了 Fetch API 来处理网络请求,如果你使用过 XMLHttpRequest 或者其他的网络 API,Fetch API 与它们十分相似。

Fetch

下面我们写一个例子,读取火币网的比特币实时数据 API 中的数据。为了获取实时数据,示例中将会每一秒获取一次数据。

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class HelloWorld extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ticker: {}
    };
    setInterval(() => {
      fetch('http://api.huobi.com/staticmarket/ticker_btc_json.js')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({ticker: responseJson.ticker});
      })
      .catch((error) => {
        console.error(error);
      });
    }, 1000)
  }
  render() {
    let ticker = this.state.ticker
    return (
      <View style={{paddingTop: 22}}>
        <Text>High: {ticker ? ticker.high : ''}</Text>
        <Text>Low: {ticker ? ticker.low : ''}</Text>
        <Text>Last: {ticker ? ticker.last : ''}</Text>
        <Text>Vol: {ticker ? ticker.vol : ''}</Text>
        <Text>Buy: {ticker ? ticker.buy : ''}</Text>
        <Text>Sell: {ticker ? ticker.sell : ''}</Text>
      </View>
    );
  }
}

AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
比特币实时行情数据示例

WebSocket

React Native 同时也支持 WebSocket 连接方式进行网络通信,与在 Web 开发时使用 WebSocket 类似。

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

下一篇:React Native 上手 - 8.使用导航组件

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容