React Native 使用fetch進行網絡請求
1.介紹
Fetch 請求網絡的方式和web請求網絡的方式是一致的,可用於滿足開發者訪問網絡的需求。
2.get請求
2-1 在構造方法中初始化數據
constructor(props){
super(props)
this.state = {
dataSource:new ListView.DataSource({
rowHasChanged:((row1,row2) => (row1 !== row2))
}),
load:false
}
}
2-2 在componentDidMount()方法中請求網絡,獲得數據源
componentDidMount()頁面加載完成後執行
getData(){
fetch('http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/2',{
method:'GET',//get請求
})
.then((response) => response.json())//獲取數據
.then((responseText) => {//處理數據
this.setState({//刷新界面
load:true,
dataSource:this.state.dataSource.cloneWithRows(responseText.results)
})
})
.catch((error) => {//獲取數據錯誤時執行
console.warn(error)
}).done()
}
Json 數據
2-3 渲染界面
render(){ if (!this.state.load){ return this.renderLoading() } return this.renderListView(this.state.dataSource) } //頁面加載時執行
renderLoading(){ return ( <View style={styles.load}> <Text>正在加載中...</Text> </View> ) } //數據加載完畢,獲取數據時執行
renderListView(dataSource){ return ( <ListView dataSource={dataSource} renderRow={this.renderRow}> </ListView> ) } //渲染界面 renderRow(rowData){ return ( <View style={styles.container}> <Image source={{ uri: rowData.url }} style={{ width: width, height: height / 2, marginTop: 5 }}></Image> </View> ) } 2-4 樣式
const styles = StyleSheet.constructor({ container:{ flex:1, }, load:{ flex:1, justifyContent:'center', alignItems:'center', }, })2-5 效果: