简体   繁体   English

useRouter 在第一页加载时不起作用。 NextJS

[英]useRouter doesn't work on first page load. NextJS

Basically, I have these two pages, a homepage and a dashboard.基本上,我有这两个页面,一个主页和一个仪表板。 Every time the homepage is loaded I want to check if the user is logged in to the app.每次加载主页时,我都想检查用户是否登录到应用程序。 If the user is logged, he/she should be redirected to the dashboard.如果用户已登录,他/她应该被重定向到仪表板。 As far as I know, this code should do the job:据我所知,这段代码应该可以完成这项工作:

  const { auth } = useAuth();
  const router = useRouter();

  useEffect(() => {
    let mounted = true;
    if (auth != null && mounted) {
      console.log(auth);
      router.push("/dashboard");
    }
    return () => (mounted = false);
  }, []);

However, the code above doesn't work on page load nor page refresh.但是,上面的代码不适用于页面加载或页面刷新。 The problem is that I need it to work on page load, and that code only works when a fast refresh occurs.问题是我需要它来处理页面加载,并且该代码仅在发生快速刷新时才有效。 I would appreciate any suggestion on how to work this out.我将不胜感激有关如何解决此问题的任何建议。

As mentioned in the comments, you'll need to add auth to the useEffect 's dependency array to ensure it runs when that variable is set.正如评论中提到的,您需要将auth添加到useEffect的依赖数组中,以确保它在设置该变量时运行。

const { auth } = useAuth();
const router = useRouter();

useEffect(() => {
    let mounted = true;
    if (auth != null && mounted) {
      console.log(auth);
      router.push("/dashboard");
    }
    return () => (mounted = false);
}, [auth]);

Not specific to the OP's auth error, but similar to the title.不特定于 OP 的身份验证错误,但类似于标题。

I found that useRouter wasn't working on page load after a refresh, but it would work if the development environment performed a background refresh when code changed or when the user navigated to the page using Links.我发现 useRouter 在刷新后无法处理页面加载,但如果开发环境在代码更改或用户使用链接导航到页面时执行后台刷新,它将起作用。

It turns out you have to watch the router.query property in a useEffect to catch when it updates and set the property in a state variable or execute the page-load code within the same useEffect.事实证明,您必须观察 useEffect 中的 router.query 属性以捕捉它何时更新并在 state 变量中设置该属性,或者在同一 useEffect 中执行页面加载代码。

  const [id, setID] = useState();
  const router = useRouter();

  // fire on load
  useEffect(() => {
    const { id } = router.query
    console.log(id); // won't be set on hard refresh
  }, []);

  // fire when router.query is updated
  useEffect(() => {
    const { id } = router.query
    setID(id);
  }, [router.query]);
  
  // this works with the second example useEffect, not the first
  return <div>{id}</div>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM