在Next.js中,当使用带有动态路由的next-translate i18n插件时,它不适用于非默认的区域设置.<



在Next.js中,当使用带有动态路由的next-translatei18n插件时,它不能使用非默认的区域设置

我有两个区域设置。阿拉伯语"ar"和英语"en"。默认区域设置为"ar"

当我访问这个URL时,例如:domain.com/post/1,它会像预期的那样出现,并显示阿拉伯语内容。

另一方面,当我试图通过这个URL访问同一篇文章的英文版:domain.com/en/post/1时,它不出现并给出404(未找到)错误。

如何解决这个问题?

下面是一个完整的示例,表示如何在Next.js中使用带有动态路由的text-translatei18n国际化插件时为默认和非默认区域设置生成动态路径:

// File: lib/local-data.js
import fs from "fs";
import path from "path";
export async function getLocalJsonData(localJsonFilePath) {
// Get the path of the json file
const filePath = path.join(process.cwd(), localJsonFilePath);
// Read the json file
const fileContent = fs.readFileSync(filePath, "utf8");
// Parse data as json
const jsonData = JSON.parse(fileContent);
return jsonData;
}

.

// File: pages/post/[postId].js
import { getLocalJsonData } from "@/lib/local-data";
import useTranslation from "next-translate/useTranslation";
export async function getStaticPaths({ locales }) {
// Reading local json data.
// Supposing you store your data in a json file within the project
const posts = await getLocalJsonData("/data/json/posts.json");
// Generate dynamic paths for default and non-default locales.
const paths = posts.flatMap((post) =>
locales.map((locale) => ({
params: { postId: String(post.id) },
locale,
}))
);
// { fallback: false } means other routes should 404.
return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
// Reading local json data.
const posts = await getLocalJsonData("/data/json/posts.json");
// Return the value of the first element that passes the given test.
const postObject = posts.find((post) => {
return String(post.id) === String(params.postId);
});
return { props: { postObject } };
}

export default function Post({ postObject }) {
({ t: translate, lang: currentLocale } = useTranslation());
return (
<>
<h1>
{currentLocale === "ar"
? postObject.ar?.title
: postObject.en?.title}
</h1>
<div>
{currentLocale === "ar"
? postObject.ar?.content
: postObject.en?.content}
</div>
</>
);
}

最新更新