我正在使用Gatsby,我想创建一个使用多语言的单一站点,到目前为止,我已经定义了包含以下内容的pages/index.js:
import React from "react"
import Layout from "../components/layout/layout"
import BGTState from "../context/bgt/bgtState"
import { Router } from "@reach/router"
import Home from "../components/pages/home"
import Collection from "../components/pages/collection"
import NotFound from "../components/pages/404"
const IndexPage = () => {
return (
<BGTState>
<Layout>
<Router>
<Home path="/" />
<Collection path="collection/:id" />
<NotFound default />
</Router>
</Layout>
</BGTState>
)
}
export default IndexPage我将gatsby-node.js修改为:
// Implement the Gatsby API onCreatePage. This is
// called after every page is created.
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
if (page.path === "/") {
page.matchPath = "/*"
createPage(page)
}
}每个请求都会在index.js上转发,但有一个问题。我使用的插件gatsby-plugin-intl会给url添加一个动态前缀,比如:http://localhost:3001/en/
如果我访问http://localhost:3001/en/,则会显示NotFound组件,因为没有与url匹配的路由。有没有办法给url加上前缀,并将所有内容重新路由到正确的组件?
发布于 2020-12-14 18:53:30
为什么要使用client-only路由/包装<Router>内的所有内容
我不知道在您的场景中更改gatsby-node.js的目标是什么:
// Implement the Gatsby API onCreatePage. This is
// called after every page is created.
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
if (page.path === "/") {
page.matchPath = "/*"
createPage(page)
}
}如果您不使用仅客户端路由,则可以将其删除。
这是一个广泛的问题,但只需定义您的语言和翻译文件。在你的gatsby-config.js中
plugins: [
{
resolve: `gatsby-plugin-intl`,
options: {
// language JSON resource path
path: `${__dirname}/src/intl`,
// supported language
languages: [`en`,`es`],
// language file path
defaultLanguage: `en`,
// option to redirect to `/en` when connecting `/`
redirect: true,
},
},
]useIntl钩子将捕获内部请求,因此,您只需担心视图,而忘记路由:
import React from "react"
import { useIntl, Link, FormattedMessage } from "gatsby-plugin-intl"
const IndexPage = () => {
const intl = useIntl()
return (
<Layout>
<SEO title={intl.formatMessage({ id: "title" })}/>
<Link to="/page-2/">
<FormattedMessage id="go_page2" />
</Link>
</Layout>
)
}
export default IndexPage您的Collection组件应该是包装在/page文件夹中的页面,或者是具有特定id的自定义集合。如果是page is dynamically created,您应该管理gatsby-node.js中的定制,在这种情况下,它应该是该场景中的集合模板。
要在页面之间进行链接,我建议使用page-queries来获取创建组件所需的数据。你的页面应该是这样的:
const IndexPage = () => {
return (
<BGTState>
<Layout>
<Link to="/"> // home path
<Link to="collection/1">
</Layout>
</BGTState>
)
}
export default IndexPageGatsby将自动处理404个页面,重定向所有错误的请求(开发中将显示页面列表)。您的其他路由应该使用内置的<Link>组件(从React的@reach/router扩展而来)来管理。
要使<Link to="collection/1">链接动态化,应该像我前面说过的那样进行页面查询,以获得适当的链接,以便从数据构建定制的动态<Link>。
一旦你安装了gatsby-plugin-intl插件,你的所有页面都会自动添加前缀,然而,要使用<Link>或navigate指向它们,你需要获取当前语言并添加前缀:
export const YourComponent = props => {
const { locale } = useIntl(); // here you are getting the current language
return <Link to={`${locale}/your/path`}>Your Link</Link>;
};因为useIntl()是插件提供的自定义钩子,所以locale的值将在您更改语言时自动设置。
https://stackoverflow.com/questions/65286894
复制相似问题