首页 > 解决方案 > 获取 Gatsby 中所有现有页面路由的数组

问题描述

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

标签: javascripthtmlreactjsgatsbyserver-side-rendering

解决方案


Gatsby 将您告诉它的每个页面的信息(通过pages文件夹或createPageAPI)公开为名为allSitePage. 我倾向于在我的大多数项目中创建这样的钩子,因此很容易获得这些信息:

import { graphql, useStaticQuery } from "gatsby"

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

  return nodes.map(node => node.path)
}

推荐阅读