我正在使用useSWR来获取数据,然后使用数据,我想通过使用 reduce 来获得总数。如果我 console.log 输出它的值,它可以正常工作,但是一旦我尝试使用该值设置状态,我就会收到“Too may re-renders”消息。
import Admin from "../../../components/admin/Admin";
import { useRouter } from "next/router";
import styles from "../../../styles/Dashboard.module.css";
import { getSession, useSession } from "next-auth/client";
import { useState } from "react";
/* BOOTSTRAP */
import Col from "react-bootstrap/Col";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Spinner from "react-bootstrap/Spinner";
import Table from "react-bootstrap/Table";
import useSWR from "swr";
import axios from "axios";
const General = () => {
const [session, loading] = useSession();
const [adults, setAdults] = useState(null);
const router = useRouter();
const { id } = router.query;
const fetcher = (url) =>
axios
.get(url, {
headers: { Authorization: "Bearer " + session.user.servertoken },
})
.then((res) => res.data);
const { data, error } = useSWR(
`http://localhost:8000/api/admin/general/${id}`,
fetcher
);
if (data) {
const adults = data.map((a) => a.adults);
const reducer = (accumlator, item) => {
return accumlator + item;
};
const totalAdults = adults.reduce(reducer, 0);
setAdults(totalAdults);
}
return (
<Admin>
<div className={styles.admin_banner}>
<Container fluid>
<Row>
<Col>
<h2>Bookings</h2>
<h6>
{adults}
</h6>
</Col>
</Row>
</Container>
</div>
<Container fluid>
<Row>
<Col>
<div className={styles.admin_container}>
{!error && !data && (
<Spinner animation="border" role="status">
<span className="sr-only">Loading...</span>
</Spinner>
)}
{!error && data && (
<Table responsive="md">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
{data &&
!error &&
data.map((d) => (
<tr key={d._id}>
<td>
{d.firstName} {d.lastName}
</td>
</tr>
))}
</tbody>
</Table>
)}
</div>
</Col>
</Row>
</Container>
</Admin>
);
};
export async function getServerSideProps(context) {
const session = await getSession({
req: context.req,
});
if (!session) {
return {
redirect: {
destination: "/admin",
permanent: false,
},
};
} else {
return { props: session };
}
}
export default General;