【问题标题】:Gatsby JS url path is not updating correctlyGatsby JS url 路径未正确更新
【发布时间】:2020-06-29 15:43:00
【问题描述】:

我正在使用 Gatsby JS,由于某种原因,新页面的 url 被添加到当前 url 的末尾。我会尽力解释。这是一个活生生的例子:

在此页面上:https://nyxo.app/week/understanding-your-sleep 是睡眠辅导周的课程列表。当用户点击课程时,url 应该变成https://nyxo.app/lesson/lesson-name

目前,这种情况正在发生:https://nyxo.app/week/understanding-your-sleep/lesson/lesson-name.,它会导致 404。

这是gatsby-node.js 文件,显示了模板的创建方式。

// gatsby-node.js

  weeks.forEach((week: Week) => {
    createPage({
      path: `week/${week.node.slug}`,
      component: path.resolve(`./src/templates/week.tsx`),
      context: {
        slug: week.node.slug,
        locale: "en-US",
      },
    })
  })

lessons.forEach((lesson: Lesson) => {
    createPage({
      path: `lesson/${lesson.node.slug}`,
      component: path.resolve(`./src/templates/lesson.tsx`),
      context: {
        slug: lesson.node.slug,
      },
    })
  })

这是 Weeks 页面的模板文件。您可以在课程和课程名称的顶部看到路径不包括周和周名称。

// week.tsx template

{week.lessons.map((lesson: any) => (
     <LessonCard
      authors={[{ name: "testi", fixed: null }]}
      key={lesson.slug}
      path={`lesson/${lesson.slug}`} // the path to the lesson file
      excerpt={""}
      name={lesson.lessonName}
      readingTime={lesson.lessonContent.fields.readingTime.text}
     />
))}

这才刚刚开始,我不知道为什么,但我想看看其他人是否经历过这种情况以及他们是如何克服的。这个问题似乎仅限于模板。我感谢任何帮助/建议。 ✌️

【问题讨论】:

    标签: reactjs gatsby


    【解决方案1】:

    您的路径和 slug 必须以斜杠 (/) 开头,例如:

     <LessonCard
      authors={[{ name: "testi", fixed: null }]}
      key={lesson.slug}
      path={`/lesson/${lesson.slug}`} // the path to the lesson file
      excerpt={""}
      name={lesson.lessonName}
      readingTime={lesson.lessonContent.fields.readingTime.text}
     />
    

    如果您的字符串路径不以斜杠开头,它将连接为相对路径。

    此外,为了避免可能的内聚问题,同样,您的 createPage 函数必须包含斜线路径,例如:

      path: `/lesson/${lesson.node.slug}`,
    

    【讨论】:

    • 完美运行!谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2015-03-08
    • 2021-11-22
    • 2019-12-20
    • 1970-01-01
    相关资源
    最近更新 更多