【发布时间】:2021-08-31 15:45:55
【问题描述】:
我有这个错误:未捕获的错误:超过最大更新深度。当组件在 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>
);
};
【问题讨论】:
-
如果 el 始终为空字符串,key={el} 看起来是错误的,也许使用一些唯一的 id + 索引作为键?
-
拨打
onPaginationChange会发生什么?我们能看到父组件吗? -
const [pagination, setPagination] = useState({ start: 0, end: showPerPage, }); const onPaginationChange = (start, end) => { setPagination({ start, end }); }; {list.slice(pagination.start, pagination.end).map((post) => (
#{post.id}
))} -
请edit您的问题并格式化您的代码而不是评论,@samir。
-
我更新了代码,我注意到只有 useEffect 的问题。没有 useEffect 是否可能。实际上我是新的反应。非常感谢你的帮助
标签: reactjs typescript react-hooks