我是 Next.js/React 的新手。
在渲染任何组件之前,我试图首先检查用户是否已经登录(通过 Laravel API)。但是,index.js
(仪表板)在 axios
完成检查我的 API 之前已经呈现。如果用户未通过身份验证,我想首先将用户重定向到登录页面。有什么建议吗?
在pages/_app.js
function MyApp({ Component, pageProps }) {
const checkLoginStatus = () => {
axios
.get('http://localhost:8001/api/v1/auth-check', { withCredentials: true })
.then(response => {
console.log(response)
if (!response.data.user) {
return <Redirect to="/" />
}
})
.catch(error => {
console.log('Login error', error);
});
}
useEffect(() => {
checkLoginStatus();
}, []);
return <>
<Head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0" />
<meta charSet="UTF-8" />
</Head>
<Component {...pageProps} />
</>
}
redirect.js
import { useRouter } from 'next/router'
import { useEffect } from 'react';
export default function Redirect({ to }) {
const router = useRouter();
useEffect(() => {
router.push('login?url=' + to)
}, [to])
return null;
}
index.js
return <>
<Head>
<title>Dashboard</title>
</Head>
<div className="wrapper">
<Sidebar />
<div className="main-panel">
<Navbar title="Dashboard" link="/" />
</div>
</div>
</>