【发布时间】:2020-08-09 17:53:12
【问题描述】:
我是一名试图掌握 React 窍门的学生。到目前为止,我希望能够将从 API 接收的数据数组切割成块,以便以后可以使用分页效果。我无法弄清楚为什么函数 arrayChunk() 最终会导致过多的渲染。如何设置我的函数以将 chunkedArray 推入 setChunkedYearArray? 这是我的完整代码:
import React, { useState, useEffect } from 'react';
import InformationBox from '../../component/InformationBox/InformationBox';
import arrowButton from '../../assets/arrow-button.svg';
const InformationBoxLayout = (props) => {
const [activeYear, setActiveYear] = useState([]);
const [chunkedYearArray, setChunkedYearArray] = useState([]);
useEffect(() => {
axios
.get('http://www.mocky.io/v2/5ea446a43000005900ce2ca3')
.then((response) =>
setActiveYear(
response.data.timelineInfo.filter((item) => item.year === '2018')
)
);
}, []);
const arrayChunk = (array, chunkSize) => {
const chunkedArray = [];
let clonedArray = [...array];
const splitPieces = Math.ceil(clonedArray.length / chunkSize);
for (let i = 0; i < splitPieces; i++) {
chunkedArray.push(clonedArray.splice(0, chunkSize));
}
setChunkedYearArray(chunkedArray);
};
return (
<div className={style.infoBoxLayoutStyle}>
<button className={style.leftArrow}>
<img src={arrowButton} alt='previous-page-button' />
</button>
{activeYear.length > 6
? arrayChunk(activeYear, 6)
: console.log('no split')}
<button className={style.rightArrow}>
<img
src={arrowButton}
alt='next-page-button'
className={style.rotateArrowRight}
/>
</button>
</div>
);
};
export default InformationBoxLayout;
【问题讨论】:
标签: reactjs react-hooks rerender use-state