react如何修改循環(huán)數(shù)組對(duì)象的數(shù)據(jù)
react修改循環(huán)數(shù)組對(duì)象的數(shù)據(jù)
問(wèn)題描述
做一個(gè)消息評(píng)論列表,針對(duì)具體某一個(gè)消息,里面有“收藏”和“點(diǎn)贊”功能,但是發(fā)現(xiàn)直接修改對(duì)象的樹形,無(wú)法改變視圖,因此做了筆記,方便后續(xù)學(xué)習(xí)
解決辦法
循環(huán)遍歷所有的對(duì)象,然后修改對(duì)應(yīng)的值,重新設(shè)置 數(shù)組對(duì)象
案例說(shuō)明
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數(shù)據(jù)
state = {
isEdit: false
}
// 異步獲取 JS 普通對(duì)象,并綁定在props上當(dāng)服務(wù)渲染時(shí), 我是最先執(zhí)行的聲明周期函數(shù) first
static async getInitialProps(props) {
// 后面我來(lái)添加promise來(lái)模擬ajax請(qǐng)求,暫時(shí)讓你更容易理解
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'
}
]
};
}
// 構(gòu)造函數(shù), 我是 second
constructor(props) {
super(props);
let {username} = this.props;
console.log('huangbiao', username)
}
// 頁(yè)面加載完了,設(shè)置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
})
}
// 離開頁(yè)面處理的邏輯 我是 Last
componentWillUnmount () {
}
// 頁(yè)面跳轉(zhuǎn)到首頁(yè)
goHomePage () {
Router.push('/profile');
}
// 收藏
collectAction (messageObj, eventObj) {
let { messageList } = this.state;
// 循環(huán)遍歷 state中的 數(shù)組對(duì)象
let newListData = messageList.map(function(item, idx){
if (item.id === messageObj.id) {
// 改變值
return {
...item,
isCollect: !messageObj.isCollect
}
} else {
return item;
}
});
// 變化之后的 JSON數(shù)組,重新賦值
this.setState({
messageList: newListData
})
}
// 點(diǎn)贊
complimentAction(messageObj, index, eventObj) {
let { messageList } = this.state;
// 修改具體數(shù)組對(duì)象中的值
messageList[index]['isCompliment'] = !messageList[index]['isCompliment'];
// 將修改后的數(shù)組對(duì)象克隆,然后再重新賦值
// let newListData = JSON.parse(JSON.stringify(messageList));
let newListData = messageList;
this.setState({
messageList: newListData
})
}
// 獲取用戶的評(píng)論列表
getMessageListHtml () {
const that = this;
let { messageList } = this.state;
// 因?yàn)?messageList 是異步加載進(jìn)來(lái)的,所以最開始,是undefined
if (!messageList) {
messageList = [];
}
return messageList.map(function(messageObj, index){
return (
<div className={styles['message-container']} key={messageObj.id}>
<div className={styles.portrait}>
[外鏈圖片轉(zhuǎn)存失敗(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']}>
{/* 點(diǎn)贊 */}
{
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使用循環(huán)并實(shí)現(xiàn)刪除和修改
在React當(dāng)中如何使用for循環(huán)對(duì)當(dāng)前的數(shù)據(jù)進(jìn)行遍歷:
這4個(gè)組件是自己一個(gè)個(gè)寫進(jìn)來(lái)的,因該根據(jù)數(shù)據(jù)的多少遍歷出來(lái)對(duì)應(yīng)的一個(gè)結(jié)果:

例如:遍歷Persons時(shí)應(yīng)該給我們返回一個(gè)對(duì)應(yīng)的組件,而不是有一個(gè)寫一個(gè)

在React中遍歷需要使用正常的js語(yǔ)法(對(duì)應(yīng)的邏輯要寫在花括號(hào)里面)


解決此問(wèn)題:添加key值屬性,key里面必須有獨(dú)一的標(biāo)識(shí)

這樣就給每一個(gè)元素標(biāo)出了key值;
既然現(xiàn)在有用了下標(biāo),就可以給當(dāng)前的組件添加對(duì)應(yīng)的事件,比如現(xiàn)在添加刪除的事件,點(diǎn)擊某一個(gè)東西可以刪除掉;

上述代碼需要調(diào)整的地方,因?yàn)樵赗eact當(dāng)中都在使用ES6的語(yǔ)法,ES6提供了一個(gè)操作運(yùn)算符,如果后期往數(shù)組里面添加?xùn)|西就會(huì)非常方便:

還有需要做的事情就是更改當(dāng)前組件的一個(gè)內(nèi)容:

這之前給person的每個(gè)對(duì)象賦一個(gè)id屬性

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
react-pdf實(shí)現(xiàn)將pdf文件轉(zhuǎn)為圖片,用于頁(yè)面展示
這篇文章主要介紹了react-pdf實(shí)現(xiàn)將pdf文件轉(zhuǎn)為圖片,用于頁(yè)面展示問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
react中的watch監(jiān)視屬性-useEffect介紹
這篇文章主要介紹了react中的watch監(jiān)視屬性-useEffect使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
React Router 如何使用history跳轉(zhuǎn)的實(shí)現(xiàn)
這篇文章主要介紹了React Router 如何使用history跳轉(zhuǎn)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
react 跳轉(zhuǎn)后路由變了頁(yè)面沒刷新的解決方案
最近在學(xué)習(xí)React的過(guò)程中遇到了路由跳轉(zhuǎn)后頁(yè)面不刷新的問(wèn)題,本文就詳細(xì)的介紹一下解決方法,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-06-06
使用React實(shí)現(xiàn)一個(gè)簡(jiǎn)單的待辦事項(xiàng)列表的示例代碼
這篇文章我們將詳細(xì)講解如何建立一個(gè)這樣簡(jiǎn)單的列表,文章通過(guò)代碼示例介紹的非常詳細(xì),對(duì)我們的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-08-08

