【发布时间】:2021-06-16 14:34:28
【问题描述】:
我正在使用 NextJs 10.0.5 和 next-i18next 8.1.0 来本地化我的应用程序。众所周知nextJs10 有子路径路由,用于国际化路由。另外,我需要按语言更改页面名称。例如,我在 pages 文件夹中有一个 contact-us 文件。当我将语言更改为土耳其语时,我必须使用localhost:3000/tr/contact-us。但是,当语言为土耳其语时,我想使用localhost:3000/bize-ulasin 访问contact-us 页面。所以有两个网址,只有一个页面文件。
当我在 server.js 文件中使用带有 express js 的自定义路由时,它可以工作。但是,当我想访问getStaticProps 文件中getStaticProps 函数中的“语言环境”变量时,我无法访问它。当我使用localhost:3000/bize-ulasin URL 时,getStaticProps 函数返回未定义的“语言环境”变量。
server.js
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const app = next({ dev: process.env.NODE_ENV !== "production" });
const handle = app.getRequestHandler(app);
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === "/bize-ulasin") {
app.render(req, res, "/contact-us", query);
}else{
handle(req, res, parsedUrl);
}
}).listen(3000, (err) => {
if (err) throw err;
console.log("> Ready on http://localhost:3000");
});
});
/pages/contact-us-file
import { Fragment } from "react";
import Head from "next/head";
import { useTranslation } from "next-i18next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
const ContactUs = () => {
const { t } = useTranslation("common");
return (
<Fragment>
<Head>
<title>Contact-Us</title>
</Head>
</Fragment>
);
};
export const getStaticProps = async ({ locale }) => {
console.log(locale); // When I use the URL localhost: 3000/bize-ulasin, it returns undefined.
return {
props: {
...(await serverSideTranslations(locale, ["common"])),
},
};
};
export default ContactUs;
如何使用 getStaticProps 访问“locale”变量?或者,如何将以下 URL 用于同一个页面文件?
->localhost:3000/contact-us
->localhost:3000/bize-ulasin
【问题讨论】:
标签: javascript express next.js i18next next-i18next