1.7 Fetch

自己做项目中的重点知识,不是教程,如果学习的话可以拿来参考。源代码[地址][12]
[12]: https://github.com/BaiPeiHe/react-native

简介

网络编程利器-Fetch 的基本使用
Fetch 是全局的,在 React Native 任何地方都可以使用,不需要额外导入。
官网地址

测试数据 网络地址

创建页面

1、创建 FetchTest.js 文件,代码如下
2、在 index.ios.js 文件导入 FetchTest.js 文件
3、在 index.ios.js 渲染 FetchTest

// 1、FetchTest.js 文件
import React,{Component} from 'react';
import {
    View,
    Text,
    Image,
    StyleSheet,
    TouchableOpacity,
}from 'react-native';

import NavigationBar from './NavigationBar'

export default class FetchTest extends Component{

    render(){
        return(
            
                
            
        )
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'white'
    },
    text:{
        fontSize:22
    }
});
// 2、导入头文件
import FetchTest from './js/FetchTest'
// 3、渲染文件

    render() {
        return (
            
                 
                 
            
        );
    }

加载数据

注意:要在 iOS 源程序中修改配置

App Transport Security Setting
    Allow Arbitrary Loads       YES
    Exception Domain
    // 构造函数
    constructor(props){
        super(props);
        this.state={
            result:''
        }
    }
    // 请求数据
    onLoad(url){
        fetch(url)
            // 转为 json
            .then(response=>response.json())
            // 获取到 json
            .then(result=> {
                this.setState({
                    result:JSON.stringify(result)
                })
            })
            // 请求出错
            .catch(error=>{

                this.setState({

                    result:'err+' + JSON.stringify(error)
                })
            })
    }

return(
            
                

                this.onLoad('[测试数据][3]')}
                >获取数据
                提交数据
                返回结果:{this.state.result}
            
        )

提交数据

    // 提交数据的方法
    onSubmit(url,data){

        fetch(url,{
            method:'POST',
            header:{
                // 服务器返回的数据类型
                'Accept':'application/json',
                // 上传到服务的参数的类型
                'Content-Type':'application/json'
            },
            // 将 data 转换为 json 类型的字符串
            body:JSON.stringify(data)
        })
            .then(response=>response.json())
            .then(result=>{
                this.setState({
                    // 将 json 转换为字符串
                    result:JSON.stringify(result)
                })
            })
            .catch(error=>{
                this.setState({
                    result:'err + ' + JSON.stringify(error)
                })
            })

    }

    render(){
        return(
            
                
                
                this.onSubmit('[上传数据链接][4]',{userName:'小明',password:'123456'})
                      }
                >提交数据
                返回结果:{this.state.result}
            
        )
    }
}

你可能感兴趣的:(1.7 Fetch)