【问题标题】:Nextjs invalid href passed to routerNextjs 无效的 href 传递给路由器
【发布时间】:2021-10-29 18:16:36
【问题描述】:

我遇到了一个错误:

Invalid href passed to next/router: /users//posts, repeated forward slashes (//) or backlashes \ are not valid in the href

我明白为什么会这样

handleClick = () => {
  // some code
  router.push(`/users/${userId}/posts`)
}

userId 是异步获取的,因此在编译期间它不存在导致router.push('/users//posts')。但是,这段代码在handleClick 内,在按钮点击时触发。

我该如何解决这个问题?

【问题讨论】:

  • 这与编译无关,运行时userId为空,那是你的错误。
  • 您能否提供声明/设置userId 的其余代码?

标签: next.js server-side-rendering


【解决方案1】:

这实际上与router.push() 无关,而是我的导航栏。问题是我的导航栏的href是/users/[userId]/postsuserId没有填写

【讨论】:

    【解决方案2】:
    handleClick = () => {
      // some code
      //check link you are pushing
      console.log(`/users/${userId}/posts`)
      //router.push(`/users/${userId}/posts`)
    }
    

    您的链接中不能有//,调试{userId},认为它未定义,这就是出现错误的原因。

    附:如果userId 是异步的,则将if condition 放在router.push 之前

    【讨论】:

      【解决方案3】:

      如果userId是异步获取的,那么调用该函数的函数和组件是什么样的?

      你在handleClick函数中有router.push函数,那么我猜你需要为userId传递一个参数。

      <SomeComponent onClick={() => handleClick(userId)} />
      

      函数看起来像:

      const handleClick = (userId) => {
        router.push(`/users/${userId}/posts`);
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        • 2022-01-15
        • 1970-01-01
        • 2020-06-03
        • 2022-01-17
        • 2023-04-03
        相关资源
        最近更新 更多