日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

react如何修改循環數組對象的數據_React

作者:胖鵝68 ? 更新時間: 2022-12-29 編程語言

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: 'zhangsan@163.com',
            "messageList": [
                {
                    id: 1,
                    email: 'Yijun Liu@163.com',
                    message: 'Just setting up my Twitter.111111',
                    date: '2019-5-18 11:33:56'
                },
                {
                    id: 2,
                    email: 'Yijun Liu@163.com',
                    message: 'Just setting up my Twitter.222222',
                    date: '2019-5-18 11:33:56'
                },
                {
                    id: 3,
                    email: 'Yijun Liu@163.com',
                    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使用循環并實現刪除和修改

在React當中如何使用for循環對當前的數據進行遍歷:

這4個組件是自己一個個寫進來的,因該根據數據的多少遍歷出來對應的一個結果:

例如:遍歷Persons時應該給我們返回一個對應的組件,而不是有一個寫一個

在React中遍歷需要使用正常的js語法(對應的邏輯要寫在花括號里面)

解決此問題:添加key值屬性,key里面必須有獨一的標識

這樣就給每一個元素標出了key值;

既然現在有用了下標,就可以給當前的組件添加對應的事件,比如現在添加刪除的事件,點擊某一個東西可以刪除掉;

上述代碼需要調整的地方,因為在React當中都在使用ES6的語法,ES6提供了一個操作運算符,如果后期往數組里面添加東西就會非常方便:

還有需要做的事情就是更改當前組件的一個內容:

組件

這之前給person的每個對象賦一個id屬性

總結

原文鏈接:https://blog.csdn.net/hbiao68/article/details/94437647

欄目分類
最近更新