React Native_手把手教你做项目(三.封装网络请求)

使用Mock假数据我这出现点问题,不能做网络请求加载数据,不能用就算了,我们不用它了,直接使用抓包工具抓到的接口

封装网络请求

拼接请求字符串

npm install query-string –save

合并Json对象工具

npm i lodash –save

新建公共文件夹common,并创建配置文件和封装网络请求文件

这里写图片描述

config.js

'use strict'

const  config = {
    api:{
        // http://api.budejie.com/api/api_open.php?a=list&c=data&type=29
        base:'http://api.budejie.com/',
        list:'api/api_open.php',
    },
    map:{
        method:'POST',
        header:{
            'Accept':'application/json',
            'Content-Type':'application/json',
        },
        timeout:8000,
    }
}

module.exports = config

request.js

'use strict'

import Mock from 'mockjs';
import queryString from 'query-string';
import _ from 'lodash';
import config from './config';

//request是个变量,后面有个{},它就是一个对象
let request={

}

//设定params json对象
request.get = (url,params) =>{
    if(params) {
        url += "?" + queryString.stringify(params)
    }

         //发送网络请求
    return fetch(url)
        .then((response)=>response.json())
        .then((response)=>Mock.mock(response))

}

request.post = (url,body) =>{
    //合并JSON对象
    let map = _.extend(config.map,{
        body:JSON.stringify(body)
    })

    return fetch(url,map)
        .then((response)=>response.json())
        .then((response)=>Mock.mock(response))
}

module.exports = request;

使用封装的网络请求拿到数据

修改list文件

重点是网络请求部分的代码

_fetchData(){
       //发送网络请求
        request.get(config.api.base+config.api.list,{
            accessToken:'001',
            a:'list',
            c:'data',
            type:29
        }).then(
            (data) => {
                console.log(data);

                 this.setState({
                   dataSource:this.state.dataSource.cloneWithRows(data.list)
                  })

            }
        ).catch(
            (error) =>{
                console.log('err' + error);
            }
        )
    }

list.js文件全部代码

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    View,
    ListView,
    TouchableOpacity,
    Image
} from 'react-native';

import Icon from 'react-native-vector-icons/Ionicons';
import Dimensions from 'Dimensions';

const {width, height} = Dimensions.get('window');

import config from '../common/config';
import request from '../common/request';

// Mockjs 解析随机的文字
import  Mock from 'mockjs';

export default class list extends Component{
    constructor(props){
        super(props);
        this.state={
            dataSource:new ListView.DataSource({
                rowHasChanged:(r1,r2)=>r1!==r2,
            })
        }
    }

    //即将显示
    componentWillMount() {
        //加载本地数据
        // this.dsfetchData();
    }
    componentDidMount() {
        //加载网络数据
        this._fetchData();
    }

    _fetchData(){
       //发送网络请求
        request.get(config.api.base+config.api.list,{
            accessToken:'001',
            a:'list',
            c:'data',
            type:29
        }).then(
            (data) => {
                console.log(data);

                 this.setState({
                   dataSource:this.state.dataSource.cloneWithRows(data.list)
                  })

            }
        ).catch(
            (error) =>{
                console.log('err' + error);
            }
        )
    }

    dsfetchData(){
        let result = Mock.mock({
            "data|20":
                [
                    {
                        "_id":
                            "@ID",
                        "thumb":
                            "@IMG(1024x700,@COLOR(),\'\u56fe\u7247\u4e0a\u7684\u6587\u5b57\')",
                        "title":
                            "@cparagraph(1, 3)",
                        "video":
                            "\'http:\/\/v.youku.com\/v_show\/id_XMzY5ODY5MDI3Ng==.html?spm=a2h1n.8251846.0.0\'"
                    }
                ],
            "success": true
        })
        this.setState({
            dataSource:this.state.dataSource.cloneWithRows(result.data)
        })
    }

    render() {
        return (
            <View style={styles.container}>
                {/*导航条*/}
                <View style={styles.header}>
                    <Text style={styles.headerText}>
                        视频列表
                    </Text>
                </View>
                {/*列表页面*/}
                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={this._renderRow}
                    style={styles.listView}
                />
            </View>
        );
    }

    //下划线代表内部类自己用的函数,属于规范
    _renderRow=(rowData)=>{
        return (
            <TouchableOpacity>

                {/*整个Cell*/}
                <View style={styles.cellStyle}>
                    {/*标题文字*/}
                    <Text style={styles.title}>{rowData.text}</Text>


                    <Image style={styles.thumb} source={{uri:rowData.profile_image}} >

                    </Image>
                    <Icon name="ios-play"
                          size={30}
                          style={styles.play}
                    />
                    {/*点赞&评论*/}
                    <View style={styles.cellFooter}>
                        {/*点赞*/}
                        <View style={styles.footerBox}>
                            <Icon name="ios-heart-outline"
                                  size={30}
                                  style={styles.boxIcon}
                            />
                            {/*点赞文字*/}
                            <Text style={styles.boxText}>点赞</Text>
                        </View>

                        {/*评论*/}
                        <View style={styles.footerBox}>
                            <Icon name="ios-chatbubbles-outline"
                                  size={30}
                                  style={styles.boxIcon}
                            />
                            {/*点赞文字*/}
                            <Text style={styles.boxText}>评论</Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
    header:{
        // marginTop:Platform.OS == 'ios'?20:0,
        paddingTop:25,
        paddingBottom:15,
        backgroundColor:'#dddddd',
        borderBottomWidth:0.5,
        borderBottomColor:'black',
    },
    headerText:{
        fontWeight:'600',
        textAlign:'center',
        fontSize: 16,
    },
    listView:{

    },
    cellStyle:{
        width:width,
        marginTop:10,
        backgroundColor:'white',

    },
    title:{
        padding:10,
        color:'black',
        fontSize:18
    },
    thumb:{
        width:width,
        height:width*0.56,
        resizeMode:'cover'
    },
    play:{
        position:'absolute',
        bottom:100,
        right:14,
        width:46,
        height:46,
        paddingTop:8,
        paddingLeft:18,
        backgroundColor:'transparent',
        borderColor:'black',
        borderWidth:0.5,
        borderRadius:23,
    },
    cellFooter:{
        flexDirection:'row',
        justifyContent:'space-between',
        backgroundColor:'#dddddd',
    },
    footerBox:{
        padding:10,
        flexDirection:'row',
        backgroundColor:'white',
        flex:1,
        marginLeft:1,
        justifyContent:'center',

    },
    boxIcon:{
        fontSize:22,
        color:'#333',
    },
    boxText:{
        fontSize:18,
        color:'#333',
        paddingLeft:12,
        marginTop:2
    }
});

效果展示

这里写图片描述

猜你喜欢

转载自blog.csdn.net/wtdask/article/details/80907175