DGs*_*DGs 2 routes dynamic internationalization next.js
我正在使用 Next.js 实现动态路由和 i18n。我的应用程序由 2 个区域设置组成:en-US和es-MX。我正在尝试生成以下路线:
使用默认区域设置 ( en-US),我的链接指向/blog/posts/id并且我能够导航到任何 ID;例如:/blog/posts/1没有任何问题。但是,当我切换区域设置时,我的链接现在指向路线/es-MX/blog/posts/1,这又导致 404 错误 - 未找到。
我的 slug 目录由结构组成pages/blog/posts/[id].js,在这个文件中我用它getStaticPaths来生成上述语言环境的路径:
export const getStaticPaths({locales}) => {
const res = await fetch(`${server}/api/posts`);
const posts = await res.json();
const ids = posts.map((post) => post.id);
const paths = ids.map((id) => ({
params: {id: id.toString(), locale: 'en-US' },
params: {id: id.toString(), locale: 'es-MX' },
}));
return {
paths,
fallback: false,
};
}
Run Code Online (Sandbox Code Playgroud)
我打算根据当前的语言环境从 api 中提取后期翻译。除此路线外,其他所有内容(包括应用程序中的所有其他路线)均按预期工作。我缺少什么?
你遇到的问题是你正在返回localeinside params,这是错误的,locale应该在 out of 之外params,因为它可以通过context.localeand not访问context.params.locale,它适用于因为这是withdefaultLocale的默认行为,请在此处阅读更多信息。getStaticPathslocales
getStaticPaths如果您像下面这样重新设计以避免出现问题,那就更好了params:
export const getStaticPaths = async ({ locales }) => {
const res = await fetch(`${server}/api/posts`);
const posts = await res.json();
const ids = posts.map((post) => post.id);
const paths = ids
.map((id) =>
locales.map((locale) => ({
params: { id: id.toString() },
locale, //locale should not be inside `params`
}))
)
.flat(); // to avoid nested arrays
return {
paths,
fallback: false,
};
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3166 次 |
| 最近记录: |