zoukankan      html  css  js  c++  java
  • 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',
      }
    });
    View Code

    此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
  • 相关阅读:
    管理上第一是用人
    意义只存在于关系中,由其定义
    苦与累在希望面前啥也不是
    人是一切,组织是一切
    UI设计
    以理服人需要什么?
    灵活性是原则性基础上的灵活
    软件行业深层的文化属性
    自然原始分工
    把一个系统维护好需要做哪些工作?
  • 原文地址:https://www.cnblogs.com/liuw-flexi/p/11571817.html
Copyright © 2011-2022 走看看