Bil*_*ack 12 javascript internationalization next.js
我正在使用 next-i18next 构建一个具有国际化功能的 Next.js 应用程序。为我的网站的所有页面生成英语和法语页面,但具有动态路由的页面除外:(即blog/[id]/[blog-title])。对于具有动态路由的页面,会生成英语页面,但不会生成法语页面。
我应该指出,两种语言的博客条目都是相同的。因此,如果用户单击列表中的博客条目,他们将获得相同的博客条目。
当法语用户访问具有动态路由的页面时,他们会收到 404。我是 React 和 Next 的新手,所以我可能会在这里做一些愚蠢的事情。
// next-i18next.config.js
module.exports = {
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
localeDetection: true,
},
}
Run Code Online (Sandbox Code Playgroud)
//
// blog\[id]\[title]
//
export async function getStaticPaths() {
const response = await axios.get('https://api.myappi.com/blog')
const posts = response.data
const paths = posts.map((post: Props) => ({
params: { id: post.Id, title: post.Title },
}))
return { paths, fallback: false }
}
export async function getStaticProps(props: IStaticProps) {
const { id, locale } = props.params
const response = await axios.get(`https://api.myappi.com/blog/${id}`)
const post = await response.data
if (!post) {
return {
notFound: true,
}
}
return {
props: {
Id: post.Id,
Title: post.Title,
Blog: post.Blog,
DatePosted: post.DatePosted,
PostedBy: post.PostedBy,
...(await serverSideTranslations(props.locale, ['common', 'blog']))
}
}
}
Run Code Online (Sandbox Code Playgroud)
jul*_*ves 18
对于动态路由,您必须显式返回要从函数预先生成的区域设置getStaticPaths。如果不这样做,Next.js 将仅生成默认区域设置的页面。
来自国际化路由文档:
对于使用
getStaticProps动态路由的页面,需要预渲染的页面的所有区域设置变体都需要从getStaticPaths. 除了params返回的对象 之外paths,您还可以返回一个locale指定要呈现的区域设置的字段。
getStaticPaths这可以通过修改函数来为每个 slug/locale 组合生成路径来实现。
export async function getStaticPaths({ locales }) { // Get available locales from `context`
const response = await axios.get('https://api.myappi.com/blog')
const posts = response.data
const paths = posts
.map((post: Props) => locales.map((locale) => ({
params: { id: post.Id, title: post.Title },
locale // Pass locale here
})))
.flat() // Flatten array to avoid nested arrays
return { paths, fallback: false }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6269 次 |
| 最近记录: |