我有这个错误:未捕获的错误:超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,就会发生这种情况。 React 限制嵌套更新的数量以防止无限循环。
我不知道为什么会出错,有人可以帮忙吗?
App.tsx 文件:
const [showPerPage] =useState(1);
const [pagination, setPagination] = useState({ start: 0, end: showPerPage, });
const onPaginationChange = (start, end) => {
setPagination({ start, end });
};
<Grid container lg={12} xs={12} sm={12}> {list.slice(pagination.start, pagination.end).map((post) => (
<h5>{post.id}</h5> ))
}
<UsePagination
showPerPage={showPerPage}
onPaginationChange={onPaginationChange}
total={list.length} />
</Grid>
ReactJS 组件代码:UsePagination.tsx 文件
import React, { useState, useEffect } from 'react';
export const UsePagination = ({ showPerPage, onPaginationChange, total }) => {
const [counter, setCounter] = useState(1);
const [numberOfButtons] = useState(Math.ceil(total / showPerPage));
useEffect(() => {
const value = showPerPage * counter;
onPaginationChange(value - showPerPage, value);
}, [counter]);
const onButtonClick = (type) => {
if (type === 'prev') {
if (counter === 1) {
setCounter(1);
} else {
setCounter(counter - 1);
}
} else if (type === 'next') {
if (numberOfButtons === counter) {
setCounter(counter);
} else {
setCounter(counter + 1);
}
}
};
return (
<div className="d-flex justify-content-center">
<nav className="hd-pagination">
<ul className={'hd-pagination__wrapper'}>
<li className="hd-pagination__item hd-pagination__button">
<button
type="button"
data-testid="pagination-prev-button"
onClick={() => onButtonClick('prev')}
className="hd-pagination__link"
>
pre
</button>
</li>
{new Array(numberOfButtons).fill('').map((el, index) => (
<li
key={el}
className={`hd-pagination__item ${index + 1 === counter ? 'active' : null}`}
>
<button
type="button"
data-testid="pagination-button-number"
data-automation-id="instantCheckout-pagination-button"
onClick={() => setCounter(index + 1)}
className={`hd-pagination__link`}
>
{index + 1}
</button>
</li>
))}
<li className={'hd-pagination__item hd-pagination__button'}>
<button
type="button"
data-testid="pagination-next-button"
onClick={() => onButtonClick('next')}
className={'hd-pagination__link'}
>
Next
</button>
</li>
</ul>
</nav>
</div>
);
};
答案 0 :(得分:1)
每当您的 componentDidMound 或 useEffect(在您的情况下为 App.tsx
文件)出现无限循环时,您都会收到该错误
为了解决您的问题,最好删除 onPaginationChange
文件的 useEffect 中的 UsePagination.tsx
函数,并将该函数添加到按钮的 onClick
事件中。
试试这样:
<button
type="button"
data-testid="pagination-button-number"
data-automation-id="instantCheckout-pagination-button"
onClick={() => {
const value = showPerPage * (index + 1)
setCounter(index + 1)
onPaginationChange(value - showPerPage, value)
}}
className={`hd-pagination__link`}
>
{index + 1}
</button>