sri*_*gde 8 router reactjs next.js use-effect
我有一个简单的应用程序,如果用户登录并且用户手动尝试转到 /signin 页面,他将被重定向到索引页面。我正在使用 nextjs,为了实现这一点,我在 useEffect 中运行一个函数,其中布尔值被检查为 true,如果我使用 Router.push 用于将用户重定向到索引页面。该功能运行良好,在重定向到索引页面之前我看到登录页面有几毫秒的时间。这是为什么?是不是因为每次组件渲染后都会调用useEffect?基本上我想在渲染组件之前运行该代码,并在渲染组件之后运行 useEffect 。我基本上想运行像 componentWillMount 这样的代码。我如何在功能组件中做到这一点?或者还有其他解决方案吗?
const SigninComponent = () => {
useEffect(() => {
isAuth() && Router.push(`/`);
}, []);
return(
// components
);
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*ani 12
那是因为useEffect只有在组件安装后才会运行。
您可以使用不同的解决方案:
isAuth()返回 false,则您将呈现其他内容(很可能是登录表单)。const SigninComponent = () => {
const [loading, setLoading] = useState(true);
useEffect(() => {
if(isAuth()){
Router.push(`/`);
}else{
setLoading(false)
}
}, []);
if(!loading){
return <Login />
}else{
return <MyloaderComponent />
}
}
Run Code Online (Sandbox Code Playgroud)
getServerSideProps并运行isAuth()服务器端而不是客户端,如果您在getServerSideProps组件内部重定向,则根本不会呈现。(只能在页面中使用getServerSideProps)export const getServerSideProps = async (ctx) => {
const auth = await isAuth() // or other any logic, like read cookies...
if (!auth) {
const { res } = ctx;
res.setHeader("location", "/");
res.statusCode = 302;
res.end();
return;
}
return {
props: {}, // or return user
};
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6437 次 |
| 最近记录: |