获取 Gatsby 中所有现有页面路由的数组

Goo*_*123 3 html javascript reactjs server-side-rendering gatsby

我正在 Gatsby 中创建一个404页面,我想根据用户所访问的路径(不存在)向用户提供类似路径名的建议。如何获取网站中所有现有页面的数组?

cor*_*ard 6

Gatsby 将您告诉它的每个页面的信息(通过pages文件夹或createPageAPI)公开为名为 的 GraphQL 字段allSitePage。我倾向于在我的大多数项目中创建一个这样的钩子,这样就可以很容易地获取这些信息:

import { graphql, useStaticQuery } from "gatsby"

const useInternalPaths = () => {
  const {
    pages: { nodes },
  } = useStaticQuery(graphql`
    {
      pages: allSitePage {
        nodes {
          path
        }
      }
    }
  `)

  return nodes.map(node => node.path)
}
Run Code Online (Sandbox Code Playgroud)