一. 簡(jiǎn)介
應(yīng)用中不可避免會(huì)請(qǐng)求到網(wǎng)絡(luò)鼻疮,原生android開(kāi)發(fā)會(huì)使用handler機(jī)制,通過(guò)異步任務(wù)AsyncTask請(qǐng)求網(wǎng)絡(luò)府蔗,React-native擅長(zhǎng)界面處理,通過(guò)this.state來(lái)觸發(fā)萄唇。
二. 示例
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
class HomeUI extends Component {
constructor(props) { super(props);//這一句不能省略损趋,照抄即可 this.state = { movies: null, //這里放你自己定義的state變量及初始值 }; }
render(){ if (!this.state.movies) { //如果movies==null的情況 初始情況 渲染加載視圖 return this.renderLoadingView(); } //從網(wǎng)絡(luò)上獲取了數(shù)據(jù)的情況 var movie = this.state.movies[0]; return this.renderMovie(movie); }
renderLoadingView() { return ( <View style={styles.container}> <Text> 正在網(wǎng)絡(luò)上獲取電影數(shù)據(jù)…… </Text> </View> ); }
renderMovie(movie) { return ( <View style={styles.container}> <Image source={{uri: movie.posters.thumbnail}} style={styles.thumbnail} /> <View style={styles.rightContainer}> <Text style={styles.title}>標(biāo)題:{movie.title}</Text> <Text style={styles.year}>{movie.year}年</Text> </View> </View> ); } componentDidMount() { this.fetchData(); } fetchData() { fetch(REQUEST_URL) .then((response) => response.json()) .then((responseData) => { this.setState({ movies: responseData.movies, }); }) .done(); //調(diào)用了done() —— 這樣可以?huà)伋霎惓6皇呛?jiǎn)單忽略 } }
const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, thumbnail: { width: 53, height: 81, }, rightContainer: { flex: 1, }, title: { fontSize: 20, marginBottom: 8, textAlign: 'center', }, year: { textAlign: 'center', }, });
效果