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.使用導航組件

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容