使用功能组件和钩子进行反应'Error: Maximum update depth exceeded.'



我收到以下错误:

Error: Maximum update depth exceeded.

使用此组件:

const UsersPage: React.FunctionComponent<UsersPageProps> = ({
location,
history,
match,
}): JSX.Element => {
const dispatch = useDispatch();
const { search } = location;
const query = parseInt(location.search, 10);
const [currentPage, setCurrentPage] = useState<number>(
isNaN(query) || query < 0 ? 0 : query
);
const users = useSelector((state: any) => state.manageUsers.users.results);
const isLoading = useSelector((state: any) => state.manageUsers.usersLoaded);
const totalPages = useSelector(
(state: any) => state.manageUsers.users.totalPages
);
const handlePaginationChange = (
event: React.ChangeEvent<any>,
pageNumber: number
): void => {
history.push(`${match.path}?page=${pageNumber ?? 0}`);
setCurrentPage(pageNumber ?? 0);
};
const handleAddUserOnClick = () =>
dispatch(manageUsersSetNewUserAndNavigate());
const handleEditOnClick = (id) =>
dispatch(manageUsersSetActiveEditUserAndNavigate(id));
useEffect(() => {
dispatch(manageUsersLoadUsers(currentPage));
}, [currentPage]);
return (
<section className="users page">
{!isLoading && <SectionLoaderWithMessage message={"Loading users..."} />}
{isLoading && (
<React.Fragment>
<Toolbar disableGutters={true}>
<Title flex={1}>Manage Users</Title>
<Button
variant="contained"
color="secondary"
onClick={handleAddUserOnClick}
startIcon={<AddCircle />}
>
Add User
</Button>
</Toolbar>
<TableContainer component={Paper}>
<Table aria-label="table">
<TableHead>
<TableRow style={{ backgroundColor: "white" }}>
<TableCell style={{ fontWeight: "bold", minWidth: 150 }}>
Email
</TableCell>
<TableCell style={{ fontWeight: "bold", minWidth: 150 }}>
Name
</TableCell>
<TableCell style={{ fontWeight: "bold", minWidth: 150 }}>
Surname
</TableCell>
<TableCell style={{ fontWeight: "bold", minWidth: 150 }}>
Firm
</TableCell>
<TableCell style={{ fontWeight: "bold", minWidth: 150 }}>
Type
</TableCell>
<TableCell style={{ fontWeight: "bold", minWidth: 150 }}>
Enabled
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map((user, index) => (
<TableRow
key={`${user.id}-${index}`}
onClick={() => handleEditOnClick(user.id)}
hover
>
<TableCell>{user.email}</TableCell>
<TableCell>{user.name}</TableCell>
<TableCell>{user.surname}</TableCell>
<TableCell>{user.firmName}</TableCell>
<TableCell>{user.type}</TableCell>
<TableCell>{`${user.enabled}`}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<ThemedTablePagination
totalPages={totalPages}
pageNumber={currentPage}
onChange={handlePaginationChange}
/>
</TableContainer>
</React.Fragment>
)}
</section>
);
};
export default UsersPage;

我在渲染中没有看到任何更新状态以导致无限循环的地方。

函数handlePaginationChange应该在useEffect中。

目前,每次调用setCurrentPage时,它都会重新渲染组件,该组件又再次调用handlePaginationChange函数,因此再次调用setCurrentPage,循环继续。

相关内容

  • 没有找到相关文章

最新更新