ofs*_*ler 7 javascript express i18next next.js next-i18next
我使用NextJs10.0.5 和next-i18next8.1.0 来本地化我的应用程序。众所周知,nextJs10有用于国际化路由的子路径路由。此外,我需要按语言更改页面名称。例如,我contact-us在页面文件夹中有一个文件。当我将语言更改为土耳其语时,我必须使用localhost:3000/tr/contact-us. 但是,我想在语言为土耳其语时用于localhost:3000/bize-ulasin访问该页面。contact-us所以有两个 URL,只有一个页面文件。
当我在 server.js 文件中使用带有 Express js 的自定义路由时,它可以工作。但是,当我想访问文件getStaticProps中函数内的“locale”变量时contact-us,我无法访问它。当我使用 URL 时,该getStaticProps函数返回“locale”变量未定义localhost:3000/bize-ulasin。
服务器.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");
});
});
Run Code Online (Sandbox Code Playgroud)
/页面/联系我们文件
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;
Run Code Online (Sandbox Code Playgroud)
如何使用 getStaticProps 访问“locale”变量?或者,如何在同一个页面文件中使用以下 URL?
->localhost:3000/contact-us
->localhost:3000/bize-ulasin
Run Code Online (Sandbox Code Playgroud)
我今天也面临同样的问题。这就是我解决问题的方法。
首先,删除server.js文件。在 Next.JS 10 中,使用 server.js 会与 i18n 路由产生冲突,并且您将无法locale获取getStaticProps.
NextJS 有一个漂亮的方法,名为rewrites。我们将使用它来代替 server.js 文件。例如,如果您有一个名为 的页面contact-us-file,我们可以将 next.config.js 文件重写为
const { i18n } = require('./next-i18next.config')
module.exports = {
i18n,
async rewrites() {
return [
{
source: '/contact-us',
destination: '/en/contact-us-file',
},
{
source: '/bize-ulasin',
destination: '/tr/contact-us-file',
},
]
},
}Run Code Online (Sandbox Code Playgroud)
由于您已经在使用 Next-i18next,我希望您熟悉我正在导入的文件。
现在,如果您尝试导航localhost:3000/contact-us,localhost:3000/bize-ulasin您应该能够访问您的“联系我们”页面。
| 归档时间: |
|
| 查看次数: |
6482 次 |
| 最近记录: |