如何使用 nextJs 和 next-i18next 像 URL 别名一样本地化路由?

问题描述

我使用 NextJs 10.0.5 和 next-i18next 8.1.0 来本地化我的应用程序。众所周知,nextJs 10 具有用于国际化路由的子路径路由。另外,我需要按语言更改页面名称。例如,我在 pages 文件夹中有一个 contact-us 文件。当我将语言更改为土耳其语时,我必须使用 localhost:3000/tr/contact-us。但是,当语言为土耳其语时,我想使用 localhost:3000/bize-ulasin 访问 contact-us 页面。所以有两个网址,只有一个页面文件

当我在 server.js 文件中使用带有 express js 的自定义路由时,它会起作用。但是,当我想访问 getStaticProps 文件contact-us 函数中的“locale”变量时,我无法访问它。当我使用 getStaticProps URL 时,localhost:3000/bize-ulasin 函数为“locale”变量返回 undefined。

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,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

解决方法

我今天也遇到了同样的问题。这就是我解决问题的方法。

首先,删除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',]
    },}

由于您已经在使用 Next-i18next,希望您熟悉我正在导入的文件。

现在,如果您尝试导航 localhost:3000/contact-uslocalhost:3000/bize-ulasin,您应该能够访问联系我们页面。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...