我正在 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
to the matchPath
in gatsby-node.js但随后我被重定向到双前缀/sv/sv
不存在的路线。如果我告诉gatsby-plugin-react-i18next
为了不为帐户页面生成语言页面,我得到了相同的结果。
gatsby-config.js
{
resolve: `gatsby-plugin-react-i18next`,
options: {
...
},
pages: [
{
matchPath: '/:lang?/account/(.*)',
getLanguageFromPath: true
},
]
}
我们想要解决:
- 让 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>
</...>
现在继续简化:)
道具马里奥·斯克莱克 https://newbedev.com/how-to-create-dynamic-route-in-gatsby and ozburo https://github.com/microapps/gatsby-plugin-react-i18next/issues/69#issuecomment-843613097对于他们的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)