实现思路
- 设置默认值:在Next.js的路由参数处理中,可以通过
getStaticProps
或getServerSideProps
函数获取路由参数,并设置默认值。
- 多语言支持:利用
next - i18next
库来处理多语言国际化。该库提供了获取当前语言环境的方法,可根据不同语言环境动态切换默认值。
- 协调默认值与国际化配置:确保默认值对应的内容在不同语言环境下能够正确展示,需要在国际化配置文件中维护这些默认值对应的翻译。
涉及技术点
- Next.js路由参数处理:
getStaticProps
和getServerSideProps
用于获取路由参数并传递给页面组件。
- next - i18next库:用于实现多语言国际化,提供获取当前语言环境及翻译功能。
- 国际化配置文件:管理不同语言环境下的文本翻译,包括默认值对应的内容。
关键代码片段
- 页面文件([locale]/category/[categoryId]/product/[productId].js)
import { useTranslation } from 'next - i18next';
export async function getStaticProps({ params }) {
const { locale } = params;
let categoryId = params.categoryId;
let productId = params.productId;
// 设置默认值
if (!categoryId) {
categoryId = 'defaultCategoryId';
}
if (!productId) {
productId = 'defaultProductId';
}
return {
props: {
categoryId,
productId,
locale
},
revalidate: 60 // 可选,用于增量静态再生
};
}
const ProductPage = ({ categoryId, productId, locale }) => {
const { t } = useTranslation();
// 根据当前语言环境展示默认值对应的内容
const categoryName = t(`categories.${categoryId}`);
const productName = t(`products.${productId}`);
return (
<div>
<h1>{categoryName}</h1>
<p>{productName}</p>
</div>
);
};
export default ProductPage;
- 国际化配置文件(例如:public/locales/en/translations.json)
{
"categories": {
"defaultCategoryId": "Default Category Name"
},
"products": {
"defaultProductId": "Default Product Name"
}
}
- next - i18next配置文件(next - i18next.config.js)
module.exports = {
i18n: {
locales: ['en', 'zh'],
defaultLocale: 'en'
}
};