React Native
大部分 App 都離不開網(wǎng)絡資源請求。React Native 提供了 Fetch API 來處理網(wǎng)絡請求朽基,如果你使用過 XMLHttpRequest
或者其他的網(wǎng)絡 API布隔,F(xiàn)etch API 與它們十分相似。
Fetch
下面我們寫一個例子稼虎,讀取火幣網(wǎng)的比特幣實時數(shù)據(jù) API 中的數(shù)據(jù)衅檀。為了獲取實時數(shù)據(jù),示例中將會每一秒獲取一次數(shù)據(jù)霎俩。
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);
比特幣實時行情數(shù)據(jù)示例
WebSocket
React Native 同時也支持 WebSocket 連接方式進行網(wǎng)絡通信哀军,與在 Web 開發(fā)時使用 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);
};