react 修改循环数组对象的数据

文章目录

    • 问题描述
    • 解决办法
    • 案例说明

问题描述

做一个消息评论列表,针对具体某一个消息,里面有“收藏”和“点赞”功能,但是发现直接修改对象的树形,无法改变视图,因此做了笔记,方便后续学习

解决办法

循环遍历所有的对象,然后修改对应的值,重新设置 数组对象

案例说明

import * as React from 'react';
import {
    Icon,
    Button,
    Input,
    Form,
} from 'antd';
import styles from './userinfo.less';
import logo from '/static/logo.svg';
import Connection from '@/store';
import Router from 'next/router';


// @ts-ignore
@Connection(({albums, loading}) => ({
    albums: albums,
    loading: loading.effects['_user/login'],
}))
export default class UserInfo extends React.Component {

    // 定义state数据
    state = {
        isEdit: false
    }
    
    // 异步获取 JS 普通对象,并绑定在props上当服务渲染时, 我是最先执行的声明周期函数  first
    static async getInitialProps(props) {
        // 后面我来添加promise来模拟ajax请求,暂时让你更容易理解
        return {
            username: 'Yijun Liu',
            address: 'USA. University of San Francisco',
            major: 'Computer Scientis',
            email: '[email protected]',
            "messageList": [
                {
                    id: 1,
                    email: 'Yijun [email protected]',
                    message: 'Just setting up my Twitter.111111',
                    date: '2019-5-18 11:33:56'
                },
                {
                    id: 2,
                    email: 'Yijun [email protected]',
                    message: 'Just setting up my Twitter.222222',
                    date: '2019-5-18 11:33:56'
                },
                {
                    id: 3,
                    email: 'Yijun [email protected]',
                    message: 'Just setting up my Twitter.333333',
                    date: '2019-5-18 11:33:56'
                }
            ]
        };
    }

    // 构造函数, 我是 second
    constructor(props) {
        super(props);
        let {username} = this.props;
        console.log('huangbiao', username)
    }

    // 页面加载完了,设置body的背景色    我是 Third
    componentDidMount () {
        document.getElementsByTagName('body')[0].style.background = '#E7ECEF';
        let {username, address, major, email, messageList} = this.props;
        console.log('huangbiao', username)
        this.setState({
            "username": username,
            "address": address,
            "major": major,
            "email": email,
            "messageList": messageList
        })
    }


    // 离开页面处理的逻辑  我是 Last
    componentWillUnmount () {
    }

    // 页面跳转到首页
    goHomePage () {
        Router.push('/profile');
    }

     // 收藏
    collectAction (messageObj, eventObj) {
        let { messageList } = this.state;
		// 循环遍历 state中的 数组对象
        let newListData = messageList.map(function(item, idx){
            if (item.id === messageObj.id) {
				// 改变值
                return {
                    ...item, 
                    isCollect:  !messageObj.isCollect
                }
            } else {
                return item;
            }
        });
		// 变化之后的 JSON数组,重新赋值
        this.setState({
            messageList: newListData
        })
    }

    // 点赞
    complimentAction(messageObj, index, eventObj) {
        let { messageList } = this.state;
		// 修改具体数组对象中的值
        messageList[index]['isCompliment'] = !messageList[index]['isCompliment'];
		// 将修改后的数组对象克隆,然后再重新赋值
        // let newListData = JSON.parse(JSON.stringify(messageList));
        let newListData = messageList;
        this.setState({
            messageList: newListData
        })
    }

    // 获取用户的评论列表
    getMessageListHtml () {
        const that = this;
        let { messageList } = this.state;
        // 因为 messageList 是异步加载进来的,所以最开始,是undefined
        if (!messageList) {
            messageList = [];
        }
        return messageList.map(function(messageObj, index){
            return (
                <div className={styles['message-container']} key={messageObj.id}>
                    <div className={styles.portrait}>
                        [外链图片转存失败(img-aFNgwwai-1562046300900)(https://mp.csdn.net/static/logo.png)]
                    </div>
                    <div className={styles['info-container']}>
                        <div className={styles.author}>
                            {messageObj.email}
                        </div>
                        <div className={styles.theme}>
                            {messageObj.message}
                        </div>
                        <div className={styles.time}>
                            {messageObj.date}
                            <div className={styles['tool-bar']}>
                                <div className={styles['bar-btn']}>
                                    {/* 点赞 */}
                                    {
                                        messageObj.isCompliment ? 
                                        <Icon type="heart" onClick={that.complimentAction.bind(that, messageObj, index)} style={{color: 'red'}} /> 
                                        : <Icon type="heart" onClick={that.complimentAction.bind(that, messageObj, index)}/>
                                    }
                                </div>
                                <div className={styles['bar-btn']}>
                                    <Icon type="message" onClick={that.collectAction.bind(that, messageObj)}/>
                                </div>
                                <div className={styles['bar-btn']}>
                                    {/* 收藏 */}
                                    {
                                        messageObj.isCollect ? 
                                        <Icon type="star" onClick={that.collectAction.bind(that, messageObj)} style={{color: '#FEC603'}} />
                                        : <Icon type="star" onClick={that.collectAction.bind(that, messageObj)}/>
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            );
        })
    }

    render() {
        let messageListHtml = this.getMessageListHtml();
        return (
            <div className={styles['userinfo-page']}>
               
                <div className={styles['main-container']}>
                    
                    <div className={styles['main-center']}>
                        
                        {messageListHtml}
                    </div>
                </div>
            </div>
        );
    }
}

你可能感兴趣的:(react,antDesigin,dva,mobx)