React Native提供了和web標準一致的Fetch API,用於滿足開發者訪問網絡的需求。
發起網絡請求
要從任意地址獲取內容的話,只需簡單地將網址作爲參數傳遞給fetch方法即可:
fetch('https://mywebsite.com/mydata.json')
import React, { Component } from 'react';
import {
AppRegistry,
Image,ListView,
StyleSheet,
Text,
View
} from 'react-native';
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
class HttpTest extends Component {
constructor(props) {
super(props); //這一句不能省略,照抄即可
this.state = {
movies: null, //這裏放你自己定義的state變量及初始值
};
// 在ES6中,如果在自定義的函數裏使用了this關鍵字,則需要對其進行“綁定”操作,否則this的指向不對
// 像下面這行代碼一樣,在constructor中使用bind是其中一種做法(還有一些其他做法,如使用箭頭函數等)
this.fetchData = this.fetchData.bind(this);
}
render() {
if (!this.state.movies) {
return this.renderLoadingView(); //剛開始網絡數據沒有拉取下來,先展示一個加載頁面
}
var movie = this.state.movies[0];
return this.renderMovie(movie);
}
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
// 注意,這裏使用了this關鍵字,爲了保證this在調用時仍然指向當前組件,我們需要對其進行“綁定”操作
this.setState({ //調用setState,會觸發調用render,重新渲染界面
movies: responseData.movies,
});
})
.done();
}
componentDidMount() {//React組件的一個生命週期方法,組件加載完後調用。
this.fetchData();
}
renderLoadingView() {
return (
<View style={styles.container}>
<Text>
正在加載電影數據……
</Text>
</View>
);
}
renderMovie(movie){
return (
<View style={styles.container}>
<Image source={{uri:movie.posters.thumbnail}}
style={styles.thumbnail}></Image>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year} </Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection:'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
thumbnail: {
width: 53,
height: 80,
},
rightContainer:{
flex:1,
},
title:{
fontSize:20,
marginBottom:8,
textAlign:'center',
},
year:{
textAlign:'center',
},
});
AppRegistry.registerComponent('HttpTest', () => HttpTest);
運行結果:
本例子節選於: react native綜合小例子:“電影列表”。