尝试从功能组件中的后端 API 加载数据并将状态变量 chartdata
设置为响应数据。
不完全了解 hoosk 以及它们如何加载 - 我被卡住并尝试了很多东西。这是我当前返回 Rendered more hooks than during the previous render.
错误的代码:
const fetcher = (url) => fetch(url).then((res) => res.json())
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
export default function Home () {
const [session, loading] = useSession()
if (loading) return null
if (!loading && !session) {
return <>
<p>Not signed in</p>
<button onClick={() => signIn()}>Sign in</button>
</>
}
const [chartData, setChartData] = useState({data:{}});
const classes = useStyles();
let { data, error } = useSWR('/api/bookings/years/6', fetcher) //returning data correctly
if (error) return <div>Failed to load: {error}</div>
if (!data) return <div>Loading...</div>
useEffect(() => {
setChartData(data);
}) //this is causing the error
const items = [
<MonthOverMonth data={chartData.data} width={'600px'}/>,
<YearOverYearLine data={chartData.data} width={'600px'}/>,
<ByMachine data={chartData.data} width={'600px'} machine={'M-1'}/>,
<ByMachine data={chartData.data} width={'600px'} machine={'X-1 Mini'}/>,
<ByMachine data={chartData.data} width={'600px'} machine={'X-1'}/>,
]
const gridItems = items.map(item => {
return <Grid item>{item}</Grid>
})
return <>
<Head>
<title>Sales Dashboard</title>
</Head>
{session && <>
<div className={classes.root} id="charts">
<AppBar position="static">
<Toolbar>
<Typography variant="h6" className={classes.title}>
Dashboard
</Typography>
<Button color="inherit" onClick={() => signOut()}>Sign Out</Button>
</Toolbar>
</AppBar>
<div style={{ padding: '25px' }}>
<SyncButton />
<Grid container spacing={3}>
{gridItems}
</Grid>
</div>
</div>
</>
}
</>
}
如何正确更新返回数据的状态?