nextjs链接组件插值错误

Ben*_*asy 13 javascript reactjs next.js

我在 Next.js 中收到此错误:

错误:提供的“href”(/subject/[subject])值缺少要正确插入的查询值(subject)。了解更多:https://err.sh/vercel/next.js/href-interpolation-failed`

我有一个动态页面设置为/subject/[subject].tsx. 现在在我的导航中我有:

<Link href={'/subject/${subject}'} passHref><a>{subject}</a></Link>
Run Code Online (Sandbox Code Playgroud)

当我使用不同的路径访问页面时,它工作正常,但是当我按下页面上的按钮时,它会抛出错误,我想这是因为组件重新渲染。如果您转到错误中的页面,它会显示:Note: this error will only show when the next/link component is clicked not when only rendered.

我试图寻找解决方案,并尝试这样做:

<Link href={{pathname: '/subject/[subject]', query: {subject: subject}}}></Link>
Run Code Online (Sandbox Code Playgroud)

但一切都没有改变。我阅读了文档,似乎该asprop 只是一个不再使用的可选装饰器,所以我不知道这对我有什么帮助。

Ale*_*ylo 5

尝试将用户重定向到区域设置时我遇到了同样的问题。我在 中做到了useEffect。经过调查,我发现第一次渲染时router.query是空的,因此缺少 required field id。我通过使用修复它router.isReady

export const useUserLanguageRoute = () => {
  const router = useRouter()

  useEffect(() => {
    const {
      locales = [],
      locale,
      asPath,
      defaultLocale,
      pathname,
      query,
      isReady // here it is
    } = router

    const browserLanguage = window.navigator.language.slice(0, 2)

    const shouldChangeLocale =
      isReady && // and here I use it
      locale !== browserLanguage
      && locale === defaultLocale
      && locales.includes(browserLanguage)

    if (shouldChangeLocale) {
      router.push(
        {
          pathname,
          query,
        },
        asPath,
        { locale: browserLanguage }
      )
    }
  }, [router])
}
Run Code Online (Sandbox Code Playgroud)


小智 0

你最好null || undefined事先检查一下。