react native之使用 Fetch进行网络数据请求
这是一个单独的页面,可以从其他地方跳转过来。
输入语言关键字,从github检索相关数据
import React, {Component} from 'react'; import { StyleSheet, View, Text, Button, TextInput, } from 'react-native'; export default class FetchDemoPage extends Component { constructor(props){ super(props); this.state={ showText:'' } } loadData(){ let url = `https://api.github.com/search/repositories?q=${this.searchKey}`; fetch(url) .then(response => response.text()) .then(responseText => { this.setState({ showText:responseText }) }) } loadData2(){ let url = `https://api.github.com/search/repositories?q=${this.searchKey}`; fetch(url) .then(response => { if(response.ok){ return response.text(); } throw new Error('Network not ok'); }) .then(responseText => { this.setState({ showText:responseText }) }) .catch(e=>{ this.setState({ showText:e.toString() }) }) } render(){ const {navigation} = this.props; return ( <View style={styles.container}> <Text>'FetchDemoPage'</Text> <View style={styles.input_container}> <TextInput style={styles.input} onChangeText={text => { this.searchKey = text; }} /> <Button title='获取' onPress={()=>{ this.loadData2(); }} /> </View> <Text> {this.state.showText} </Text> </View> ); } } const styles = StyleSheet.create({ container:{ flex: 1, backgroundColor:'#F5FCFF', }, text:{ fontSize: 20, textAlign: 'center', margin: 10, }, input:{ height: 30, flex: 1, borderColor: 'black', borderWidth: 1, marginRight: 10, }, input_container:{ flexDirection: 'row', justifyContent: 'center', } });
此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935.
我的gitHub: (学习代码都在gitHub)
https://github.com/nwgdegitHub/