useRouter/withRouter receive undefined on query in first render

后端 未结 4 923
时光说笑
时光说笑 2021-01-05 15:01

I got a problem with my dynamic route. It look like this

[lang]/abc

I am trying to get query value from [lang] but when I using

4条回答
  •  心在旅途
    2021-01-05 15:23

    It is not possible to get a query value at the first render.

    Statically optimized pages are hydrated without provided route parameters. E.g. query is an empty object ({}).

    After hydration, Next.js will fill the query object.

    Also, at first render of a dynamic route router.asPath and router.route are equal. Once query object is available, router.asPath reflects it.

    You can rely on the query value within a useEffect hook after asPath has been changed.

    const router = useRouter();
    
    useEffect(() => {
      if (router.asPath !== router.route) {
        // router.query.lang is defined
      }
    }, [router])
    

    GitHub Issue - Add a "ready" to Router returned by "useRouter"

提交回复
热议问题