NextJS 多语言 next-intl 水合错误(已解决)

问题描述 投票:0回答:1

我正在使用 NextJS 14。当我从 next-intl 安装多语言的所有内容时,我从官方网站检查,但系统给出了几个水合错误!

  1. 创建了 i18n.ts
  2. 更新了next.config.mjs
  3. 创建了中间件.ts
  4. 创建了 [locale] 文件夹并在 [locale] 文件夹中创建了layout.tsx 和 page.tsx

所有代码如下:

i18n.ts

import {notFound} from 'next/navigation';
import {getRequestConfig} from 'next-intl/server';

// Can be imported from a shared config
const locales = ['en', 'nl', 'de', 'tr'];

export default getRequestConfig(async ({locale}) => {
    // Validate that the incoming `locale` parameter is valid
    if (!locales.includes(locale as any)) notFound();

    return {
        messages: (await import(`./languages/${locale}.json`)).default
    };
});

下一个.config.mjs

import createNextIntlPlugin from 'next-intl/plugin';

const withNextIntl = createNextIntlPlugin();

/** @type {import('next').NextConfig} */
const nextConfig = {
    images: {
        domains: [
            "avatars.githubusercontent.com",
            "lh3.googleusercontent.com",
            "res.cloudinary.com",
            "images.unsplash.com"
        ]
    }
};

export default withNextIntl(nextConfig);

中间件.ts

import createMiddleware from 'next-intl/middleware';

export default createMiddleware({
    // A list of all locales that are supported
    locales: ['en', 'nl', 'de', 'tr'],

    // Used when no locale matches
    defaultLocale: 'en'
});

export const config = {
    // Match only internationalized pathnames
    matcher: ['/', '/(en|nl|de|tr)/:path*']
};

布局.tsx

import {NextIntlClientProvider} from 'next-intl';
import {getMessages} from 'next-intl/server';

export default async function LocaleLayout({children, params: {locale}}: {
    children: React.ReactNode;
    params: {locale: string};
}) {
    // Providing all messages to the client
    // side is the easiest way to get started
    const messages = await getMessages();

    return (
        <html lang={locale}>
        <body>
        <NextIntlClientProvider messages={messages}>
            {children}
        </NextIntlClientProvider>
        </body>
        </html>
    );
}

页面.tsx

import {useTranslations} from 'next-intl';

export default function Index() {
    const t = useTranslations('home_page');
    return (
        <h1>{t('slider_title')}</h1>
    );
}

error

我检查了很多不同的网站以及问题和答案,但我找不到任何正确的答案。但我现在不知道我需要做什么?

next.js multilingual hydration nextjs14
1个回答
0
投票

我遇到了同样的问题,我创建了 [locale] 文件夹并将所有内容移至其中。我以为问题出在中间件或 next-i18n-router 的使用上,问题太简单了,我花了 4 个小时才找到它,我把loading.js 留在了 [locale] 之外。使用中间件时,似乎 [locale] 之外的所有内容都会导致问题

© www.soinside.com 2019 - 2024. All rights reserved.