我得到以下错误信息。
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,循环往复。