【问题标题】:NextJS: how to Link to new page with current page slugs?NextJS:如何使用当前页面 slug 链接到新页面?
【发布时间】:2021-05-04 10:05:55
【问题描述】:

我目前有一个这样的网址:

http://localhost:3000/courses/italian/dynamic/lessons/wenC6hgETeMHSiFNabvk http://localhost:3000/courses/[language]/dynamic/lessons/[lessonID]

我正在尝试找到一种简单的方法来访问以下.../exercises 页面。我需要做的就是将/exercises 添加到上述网址的末尾。但是,以下解决方案不起作用。显然,<Link /> 不再记得我当前页面上的 [language][lessonID] 参数是什么。

<Link href={`exercises/flashcards`} passHref>
   <a>begin</a>
</Link>

错误信息:

此时,我能想到的唯一解决方案是用所需的 slug 重写整个 URL 并将其传递到 href,但如果我需要做的只是连接我的内容,那感觉有点不必要已经有 /exercises/flashcards

我错过了什么吗?

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    您不一定需要将参数作为道具传递,您可以使用useRouter 获取当前路径,然后在Link 的href 中添加额外的位。

    import { useRouter } from 'next/router';
    
    export default function SomePage() {
        const { asPath } = useRouter();
    
        return (
            <Link href={`${asPath}/exercises/flashcards`}>
                <a>begin</a>
            </Link>
        )
    }
    

    【讨论】:

      【解决方案2】:

      如果没有人回答,这是使用我当前的 slugs 的解决方案。

      // using this nextjs function to pass the params of my url as a prop for SSR.
      export async function getServerSideProps({ params }) {
        const { language, lessonID } = params;
        const data = await fetchLesson(language, lessonID);
      
        if (!data) {
          return {
            notFound: true,
          };
        }
      
        return {
          props: { data, params }, // will be passed to the page component as props
        };
      }
      
      ---
      
      // using those above param props within this Link on my component.
      <Link
         href={`/courses/${props.params.language}/dynamic/lessons/${props.params.lessonID}/exercises/flashcards`}
         passHref
      >
        <a>begin</a>
      </Link>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 2018-08-23
        相关资源
        最近更新 更多