React-Native之(小白计划八)Fetch以及封装

封装前代码:

import React, { Component } from 'react';

import {
    StyleSheet,
    Text,
    View,
    Button,
} from 'react-native';


export default class FlatListDemo extends Component<Props> {
    constructor(props){
        super(props);
        this.state={
            result:'',//初始化数据为空
        }
    }
    static navigationOptions = {
        title: 'Fetch',
    };
    //get数据
    onLoad=(url)=>{
        fetch(url)//默认是GET
            .then(response=>response.json())//把数据解析成json格式,然后取出
            .then(result=>{
                this.setState({
                    result:JSON.stringify(result),//序列化:转换为一个 (字符串)JSON字符串
                });
            })
            .catch(error=>{
            this.setState({
                result:JSON.stringify(error),//把错误信息格式化为字符串
            });
        })
    };

    //模拟登陆Post
    onSubmit=(url,data)=>{
        fetch(url,{
            method:'POST',
            header:{
                'Accept':'application/json',//告诉服务器,我们能接受json格式的返回类型,
                'Content-Type':'application/json',//告诉服务器,我们提交的数据类型
            },
            body:JSON.stringify(data),//(把你想提交得数据序列化为json字符串类型,然后提交)body中的数据就是我们需要向服务器提交的数据,比如用户名,密码等
        })//返回 服务器处理的结果
            .then(response=>response.json())
            .then(result=>{
                this.setState({
                    result:JSON.stringify(result),//序列化:转换为一个 (字符串)JSON字符串
                });
            })
            .catch(error=> {
                this.setState({
                    result: JSON.stringify(error),//把错误信息格式化为字符串
                })
            })
    };

    render() {
        return (
            <View style={styles.container}>
                <Button
                    title={"获取数据"}
                    onPress={()=>this.onLoad('http://api.douban.com/v2/movie/top250')}
                />
                <Text/>
                <Button
                    title={"提交数据"}
                    onPress={()=>this.onSubmit('http://api.douban.com/v2/movie/top250',{username:'小白',password:'123456'})}
                />


                <Text>返回结果:{this.state.result}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    }

});

效果:


封装后代码:

1:HttpUtils页(封装的函数)
//一个 Promise 就是一个代表了异步操作最终完成或者失败的对象
export default class HttpUtils{
    static get=(url)=>{
        return new  Promise(((resolve, reject) => {//resolve 和 reject 函数被调用时,分别将promise的状态改为fulfilled(完成)或rejected(失败)
            fetch(url)//默认是GET
                .then(response=>response.json())//把数据解析成json格式,然后取出
                .then(result=>{
                       resolve(result);//表示完成
                })
                .catch(error=>{
                        reject(error);//表示失败
                })
            })
        )
    };
    static post=(url,data)=>{
        return new Promise(((resolve, reject) => {
            fetch(url,{
                method:'POST',
                header:{
                    'Accept':'application/json',//告诉服务器,我们能接受json格式的返回类型,
                    'Content-Type':'application/json',//告诉服务器,我们提交的数据类型
                },
                body:JSON.stringify(data),//(把你想提交得数据序列化为json字符串类型,然后提交)body中的数据就是我们需要向服务器提交的数据,比如用户名,密码等
            })//返回 服务器处理的结果
                .then(response=>response.json())
                .then(result=>{
                    resolve(result);
                })
                .catch(error=> {
                    reject(error);
                })
            })
        )
    }
}//数据转换成字符串 JSON.stringify(params)      //将数据JSON化 JSON.parse(responseJSON)

2:HomePage页(调用封装函数的那一页)

import React, { Component } from 'react';

import {
    StyleSheet,
    Text,
    View,
    Button,
} from 'react-native';

import HttpUtils from './HttpUtils';//把封装好的组件导入

export default class FlatListDemo extends Component<Props> {
    constructor(props){
        super(props);
        this.state={
            result:'',//初始化数据为空
        }
    }
    static navigationOptions = {
        title: 'Fetch封装',
    };
    //get数据
    onLoad=(url)=>{
        HttpUtils.get(url)//调用自定义组件方法,返回一个Promise
            .then(result=>{//then函数会返回一个新的promise
                this.setState({
                    result:JSON.stringify(result),//序列化:转换为一个 (字符串)JSON字符串
                });
            })
            .catch(error=> {
                this.setState({
                    result: JSON.stringify(error),//把错误信息格式化为字符串
                })
            })
    };

    //模拟登陆Post
    onSubmit=(url,data)=>{
        HttpUtils.post(url,data)
            .then(result=>{
                this.setState({
                    result:JSON.stringify(result),//序列化:转换为一个 (字符串)JSON字符串
                });
            })
            .catch(error=> {
                this.setState({
                    result: JSON.stringify(error),//把错误信息格式化为字符串
                })
            })
    };

    render() {
        return (
            <View style={styles.container}>
                <Button
                    title={"获取数据"}
                    onPress={()=>this.onLoad('http://api.douban.com/v2/movie/top250')}
                />
                <Text/>
                <Button
                    title={"提交数据"}
                    onPress={()=>this.onSubmit('http://api.douban.com/v2/movie/top250',{username:'小白',password:'123456'})}
                />


                <Text>返回结果:{this.state.result}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    }
});


猜你喜欢

转载自blog.csdn.net/yu_m_k/article/details/80607141