使用Gatsby-Plugin-Reaction-I18Next时,Gatsby无法找到客户端路由 [英] Gatsby can't find client routes when using gatsby-plugin-react-i18next

查看:0
本文介绍了使用Gatsby-Plugin-Reaction-I18Next时,Gatsby无法找到客户端路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Gatsby中的客户端路由与gatsby-plugin-react-i18next一起使用。当我尝试在不使用默认语言的情况下访问其中一个客户端路由时,例如,URL以/sv为前缀,则我得到的结果是该路由不存在。如果我将前缀/sv添加到路由器基本路径,则Default组件/路径可用,但Profile组件/路径不起作用。

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

src/ages/count t.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
    },
  ]
}

推荐答案

我们要解决:

  1. 使lang前缀起作用
  2. 使默认页面(无lang前缀)工作

为此,我目前使用的解决方案是:

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的方法道具。

这篇关于使用Gatsby-Plugin-Reaction-I18Next时,Gatsby无法找到客户端路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆