ReactNative官網例子練習(三)——請求網路
阿新 • • 發佈:2019-01-07
要想完成一個APP,網路請求獲取後臺的資料基本上是必須的。無論是咋Android中還是在ios中都是非常重要的部分ReactNative中當然也不例外。
React Native提供了和web標準一致的Fetch API,用於滿足開發者訪問網路的需求。如果你之前使用過XMLHttpRequest(即俗稱的ajax)或是其他的網路API,那麼Fetch用起來將會相當容易上手。這篇文件只會列出Fetch的基本用法,並不會講述太多細節,你可以使用你喜歡的搜尋引擎去搜索fetch api關鍵字以瞭解更多資訊。
簡單例子:點選按鈕返回資料賦值給text
/**
* Sample React Native App
* https ://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
} from 'react-native';
class RnWidget extends Component {
constructor(props){
super(props)
this.state={
title : "",
year : ""
};
}
getMoviesFromApiAsync() {
fetch('http://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({title : responseJson.movies[0].title
,year : responseJson.movies[0].releaseYear
});
console .log(responseJson);
})
.catch((error) => {
console.error(error);
});
};
render() {
return (
<View style={styles.container}>
<TouchableHighlight
underlayColor="rgb(181, 136, 254)"
activeOpacity={0.5}
style={{ borderRadius: 8,padding: 8,marginTop:5,backgroundColor:"#0588fe"}}
onPress={this.getMoviesFromApiAsync.bind(this)}
>
<Text style={{fontSize:20}}>點選我</Text>
</TouchableHighlight>
<Text>title:{this.state.title}</Text>
<Text>releaseYear:{this.state.year}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ffffff',
},
});
AppRegistry.registerComponent('RnWidget', () => RnWidget);
定義一個請求網路的方法getMoviesFromApiAsync()在TouchableHighlight的點選事件中呼叫。
例子中是將返回的資料儲存在state中 請求完資料後更新state的值。更新的方式就是用this.setState()方法來賦值。一開始的時候遇到了一個問題 “React this.setState is not a function”意思就是我們用的這個this對 它代表的是這個回掉本身不是我們構造方法中初始化的那個state。
解決方法:
(1)在點選給這個方法繫結this 在呼叫方法的地方 this.getMoviesFromApiAsync.bind(this) 呼叫bind(this)。
(2)在getMoviesFromApiAsync()方法中定義一個變數賦值為this 比如 var that = this;
然後再呼叫setState的地方 用that.setState();
效果圖:
帶引數的post請求:
定義一個方法在點選事件中呼叫
getpicListAsync() {
fetch('http://www.tngou.net/tnfs/api/list', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
page: '1',
rows: '10',
})
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
title : responseJson.tngou[0].title,
img : "http://tnfs.tngou.net/image"+responseJson.tngou[0].img
})
})
.catch((error) => {
console.error(error);
})
};
<TouchableHighlight
underlayColor="rgb(181, 136, 254)"
activeOpacity={0.5}
style={{ borderRadius: 8,padding: 8,marginTop:5,backgroundColor:"#0588fe"}}
onPress={this.getpicListAsync.bind(this)}
>
<Text style={{fontSize:20}}>點我點我</Text>
</TouchableHighlight>
<Text>{this.state.img}</Text>
<Image style={{width: 200, height: 200}} source={ {uri: this.state.img}}/>
效果圖: