【问题标题】:Gatsby + Reach router: best pattern for controlling client route pathsGatsby + Reach 路由器:控制客户端路由路径的最佳模式
【发布时间】:2021-05-20 03:16:08
【问题描述】:

我的目标是在使用 Gatsby (v2) 和 @reach/router 时以最佳模式启用以下类型的静态和动态路径。我遇到的问题是 Gatsby 文档设置您在每个动态路由上添加路径 /app 前缀,这不适合我的用例。

所需路径:

  • /:生成静态路由和构建时间
  • /about:生成静态路由和构建时间
  • /:username:动态路由和运行时生成
  • /:username/:postTitleSlug:动态路由和运行时生成

按照 Gatsby 文档,我有这个文件夹结构:

/pages
  index.jsx
  about.jsx
  app.jsx
/templates
  profile.jsx // for the /:username path
  post.jsx // for the /:username/:postTitleSlug path

app.jsx

const Routes = () => (
  <Router>
    <Profile path="/:username" />
    <Read path="/:username/:slug" />
  </Router>
);

gatsby-node.js

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions;

  if (page.path.match(/^\/app/)) {
    await createPage({
      path: 'app',
      matchPath: '/app/*',
      component: path.resolve('src/templates/Profile/index.js'),
    });
  }
};

是否可以展开“应用程序”命名法并在基本路径/ 之外键入一些动态路由?

FWIW,我第一次尝试的修复是让pages/index.jsx 只是一个路由器,类似于this post。这似乎是一个潜在的解决方案,但我不清楚gatsby-node.js 所需的更新。

【问题讨论】:

    标签: node.js reactjs gatsby reach-router


    【解决方案1】:
    • 对于您的/,只需在您的/pages 文件夹中创建一个 index.js 文件,Gatsby 将默认将其作为主页。
    • 对于您的 /about 页面,只需在 /pages 文件夹中创建一个about.js。由于 Gatsby 是基于文件路径的,因此它会构建您的 /about 页面。相同的方法适用于所有静态页面。

    对于client-only routes,“第一个”slug (:username) 需要由 Gatsby 处理以避免 404 错误,而第二个 (:slug) 可以由 @reach/router 处理。比如:

    // Implement the Gatsby API “onCreatePage”. This is
    // called after every page is created.
    exports.onCreatePage = async ({ page, actions }) => {
      const { createPage } = actions
    
      // page.matchPath is a special key that's used for matching pages
      // only on the client.
      if (page.path.match(/^\/user\/$/)) {
        createPage({
          ...page,
          matchPath: '/:username/*'
        })
      }
    }
    

    然后在你的模板中:

     <Router>
            <User path="/user/:username" />
            <UserAsset path="/user/:username/:slug" />
     </Router>
    

    这种方法处理/user/:username/:slug,但您可以根据自己的需要进行调整。

    或者,您可以通过使用gatsby-plugin-create-client-paths 插件来保存此解决方法,只需:

    {
      resolve: `gatsby-plugin-create-client-paths`,
      options: { prefixes: [`/username/*`] },
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-05
      • 2020-07-21
      • 2019-05-31
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多