美文网首页
React Native 上手 - 7.网络

React Native 上手 - 7.网络

作者: 范斌 | 来源:发表于2017-02-19 19:45 被阅读0次
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.使用导航组件

相关文章

网友评论

      本文标题:React Native 上手 - 7.网络

      本文链接:https://www.haomeiwen.com/subject/vsdcwttx.html