React Native_手把手教你做项目(六.点赞功能)

点赞的状态其实是保存在服务器上面的,因为没有服务器,所以仅仅模拟这个功能

因为点赞功能是在Item.js中的,所以在Item上面

Item.js

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

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

import Dimensions from 'Dimensions';
const {width, height} = Dimensions.get('window');
import Icon from 'react-native-vector-icons/Ionicons';

//导入发送网络请求
import request from '../common/request';
import config from '../common/config';

export default class item extends Component {

    constructor(props) {
        super(props);

        this.state = {
            rowData: this.props.rowData,
            up: this.props.rowData.voted,//点赞的状态其实是保存在服务器上面的,因为没有服务器,所以仅仅模拟这个功能
        }
    }

    _up = ()=> {
        let up = !this.state.up;
        //此时应该是在发送post网络请求成功后再改变状态机,此处仅仅用作模拟使用
        this.setState({
            up: up
        })
        let rowData = this.state.rowData;
        let url = config.api.base + config.api.up;

        console.log(up);

        // 以下body中的数据都是服务器返回的,因为我们试用的是模拟数据,大家仅做参考
        let body = {
            id: rowData._id,
            up: up ? 'yes' : 'no',
            accessToken: 'www'
        }
        //发送网络请求 POST
        request.post(url, body)
            .then(
                (data)=> {
                    if (data && data.success) {
                        this.setState({
                            up: up
                        })
                    } else {
                        // alert('网络错误,请稍后重试!');
                        console.log('网络错误,请稍后重试!');
                    }
                }
            ).catch(
            (err)=>{
                // alert('网络错误,请稍后重试!');
                console.log('网络错误,请稍后重试!');
            }
        )

    }

    render() {
        let rowData = this.state.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={this.state.up ? "ios-heart" : "ios-heart-outline"}
                                  size={30}
                                  onPress={this._up}
                                  style={[styles.up,this.state.up ? null : styles.down]}
                            />
                            {/*点赞文字*/}
                            <Text style={styles.boxText} onPress={this._up}>点赞</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({
    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
    },
    up:{
        fontSize:22,
        color:'red'
    },
    down:{
        fontSize:22,
        color:'#333'
    }
});

同时,因为我们没有服务器,所以还要在List.js文件的网络请求的数据中,增添点赞状态的标识

_fetchData(page) {

        if (page !== 0) {
            this.setState({
                isLoadingTail: true
            });
        } else {
            this.setState({
                isRefreshing: true
            });
        }

        this.setState({
            isLoadingTail: true
        });

        //发送网络请求
        request.get(config.api.base + config.api.list, {
            accessToken: '001',
            a: 'list',
            c: 'data',
            type: 29,
            page: page
        }).then(
            (data) => {
                //将服务器得到的数据缓存进来
                let items = cachedResult.item.slice();
                // let items = cachedResult.item.concat(data.list);//把缓存的数据进行拼接
                if (page !== 0) {//加载更多
                    items = items.concat(data.list);
                    cachedResult.nexPage += 1;
                } else {//刷新数据
                    items = data.list.concat(items);
                }
                //最后保存数据
                cachedResult.item = items;
                cachedResult.total = items.total;
                // console.log(items);
                // console.log('总数据是:' + cachedResult.total);
                // console.log('当前到了第:' + cachedResult.item.length + '个!');

                //因为点赞功能需要保存状态在服务器,我们在这里为数据源增添点赞属性

                for(var i=0;i<cachedResult.item.length;i++){
                    var voted =false;
                    cachedResult.item[i].voted =voted;
                }

                console.log(cachedResult);
                if (page !== 0) {//加载更多
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(
                            cachedResult.item
                        ),
                        isLoadingTail: false
                    });
                }else {
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(
                            cachedResult.item
                        ),
                        isRefreshing: false
                    });
                }

            }
        ).catch(//如果有错
            (error) => {
                if(page !=0){
                    this.setState({
                        isLoadingTail:false
                    })
                }else {
                    this.setState({
                        isRefreshing:false
                    })
                }
                console.log('err' + error);
            }
        )
    }

这里是增添标识

//因为点赞功能需要保存状态在服务器,我们在这里为数据源增添点赞标识

                for(var i=0;i<cachedResult.item.length;i++){
                    var voted =false;
                    cachedResult.item[i].voted =voted;
                }

因为我们还要模拟网络请求,所以记得在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',
        up:'api/up',
    },
    map:{
        method:'POST',
        header:{
            'Accept':'application/json',
            'Content-Type':'application/json',
        },
        timeout:8000,
    }
}

module.exports = config

示例:

这里写图片描述

猜你喜欢

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