NextJS国际化(i18n)路由:locale getting undefined

yhqotfr8  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(168)

我正在尝试为我的个人网站学习Next.js Internationalization (i18n) Routing。然而,locale,locales和默认locale值变得未定义。(我使用的是最新版本的Next.js)
以下是我的档案:

next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  i18n: {
    locales: ["tr", "en"],
    defaultLocale: "tr",
  },
};

module.exports = nextConfig;

字符串

locales/tr.js:

export default {
  hello: "Merhaba dünya!",
};

locales/en.js:

export default {
  hello: "Hello world!",
};

app/page.js:

"use client";
import { useRouter } from "next/navigation";

export default function Home() {
  const router = useRouter();
  const { locale, locales, defaultLocale } = router;
  console.log("Locales:", locale, locales, defaultLocale);
  console.log(router);

  return (
    <div>
      <h1>Hello world</h1>
      <p>Current locale: {locale}</p>
      <p>Default locale: {defaultLocale}</p>
      <p>Configured locales: {JSON.stringify(locales)}</p>
    </div>
  );
}

我尝试使用console.log获取信息,打印如下:

The print

最后,package.json:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "eslint": "8.45.0",
    "eslint-config-next": "13.4.12",
    "next": "13.4.12",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  }
}


我找不到哪里出错了。请帮我改正。

okxuctiv

okxuctiv1#

我注意到的一件事是你混淆了路由器。有一个next/navigation.js和一个next/router.js -两者都可以解构为useRouter。只有next/router有locale - next/navigation.js没有locale。
解决方案是不只是改变你的进口声明虽然,我只是尝试,它导致了“错误:NextRouter没有挂载。https://nextjs.org/docs/messages/next-router-not-mounted"错误。
现在我还在寻找解决方案,但答案可能在这里https://nextjs.org/docs/app/building-your-application/routing/internationalization

相关问题