【问题标题】:Gatsby can't find client routes when using gatsby-plugin-react-i18nextGatsby 使用 gatsby-plugin-react-i18next 时找不到客户端路由
【发布时间】:2021-04-24 11:19:45
【问题描述】:

我在 Gatsby 中使用客户端路由和 gatsby-plugin-react-i18next。当我尝试访问其中一个客户端路由而不使用默认语言时,例如url 以/sv 为前缀,然后我知道该路由不存在。如果我将前缀 /sv 添加到路由器基本路径,Default 组件/路径正在工作,但 Profile 组件/路径不起作用。

使用不带/sv 前缀的默认语言时,一切正常。

src/pages/account.tsx

<Router basepath={'/account'}>
  <AccountRoute path="/profile" component={Profile} />
  <Default path="/" />
</Router>

gatsby-node.js

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions
  if (page.path.match(/^\/account/)) {
    page.matchPath = "/account/*"

    createPage(page)
  }
}

我还尝试将前缀 /sv 添加到 gatsby-node.js 中的 matchPath,但随后我被重定向到双前缀 /sv/sv 路由存在。如果我告诉gatsby-plugin-react-i18next 不要为帐户页面生成语言页面,我会得到相同的结果。

gatsby-config.js

{
  resolve: `gatsby-plugin-react-i18next`,
  options: {
    ...
  },
  pages: [
    {
      matchPath: '/:lang?/account/(.*)',
      getLanguageFromPath: true
    },
  ]
}

【问题讨论】:

  • 这仍然有效吗?您遗漏了一些配置,有些不需要:gatsbyjs.com/plugins/gatsby-plugin-react-i18next 请仔细阅读文档。
  • 是的!我仍然记得让 Linux 运行的美好时光,每个问题的答案都是 RTFM。 SO 的伟大之处在于它不是手册,而是快速查找表。但是,我已经阅读了您链接的页面,并且没有提到 gatsby i18next 插件如何处理客户端路由问题。如果您知道答案,我们仍然感谢您的意见!

标签: gatsby i18next reach-router


【解决方案1】:

我们要解决:

  1. 让 lang 前缀工作
  2. 让默认页面(无语言前缀)工作

为此,我目前使用了这个解决方案:

gatsby-node.js:

function langPrefix(page) {
  return page.context.language === page.context.i18n.defaultLanguage &&
    !page.context.i18n.generateDefaultLanguagePage
    ? ''
    : `/${page.context.language}`
}



exports.onCreatePage = ({ page, actions }) => {
  const { createPage } = actions
  // Removing the ^ skips an optional /:lang prefix
  if (page.path.match(/\/app/)) {
    // adding lang if it's not the default page.
    page.matchPath = `${langPrefix(page)}/app/*`
    createPage(page)
  }
}

此外,我复制了路由来处理带有和不带有 lang 前缀的情况:

<...>
  {/* Version for default language (no /:lang/ in path) */}
  <Router basepath={`/app`}>
    <ViewerWrapper path="/:myProp" />
  </Router>
  {/* Version for explicit language (/:lang/ in path) */}
  <Router basepath={`/:lang/app`}>
    <ViewerWrapper path="/:myProp" />
  </Router>
</...>

现在继续简化 :)

Mario Skrlecozburo 推荐他们的方法。

【讨论】:

  • 我做了和你提到的一样的配置。但是localhost:8000/en-us/app/page1 它显示错误 /en-us/app/page1 还没有页面或功能。有什么指点吗?
  • 还有如何获取客户端路由页面的语言翻译内容?
猜你喜欢
  • 1970-01-01
  • 2019-05-31
  • 2022-01-11
  • 2021-10-12
  • 2021-12-10
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多