NextJS+NextI18Next映射翻译数组触发水化不匹配错误求解决
Next.js + next-i18next SSR 渲染时轮播组件翻译数组不匹配问题
我开发的Next.js应用集成了next-i18next实现国际化与SSR,其他场景均正常,但在自定义轮播组件映射翻译数组时出现 hydration 错误。为复用i18next框架,我将轮播数据存为数组,通过t('key', {returnObjects: true})获取后映射渲染。我不解的是,next-i18next的serverSideTranslations方法应该在SSR阶段就加载好对应语言的翻译数据,为什么服务端与客户端的渲染结果还会不一致?
报错信息
Error: Text content does not match server-rendered HTML. Warning: Text content did not match. Server: "" Client: "Correct defaultLocale string from the locale json" Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.
相关代码
pages/index.tsx
export const getServerSideProps: GetServerSideProps = async ({ locale }) => { return { props: { ...(await serverSideTranslations(locale ?? 'ru', ['header', 'auth_modal', 'home'])), }, }; }; export default function Home() { const { t } = useTranslation('home'); return ( <PageLayout title={title} description={description}> <BannerCarousel items={t('home:banner-carousel', { returnObjects: true })} speed={800} /> </PageLayout> ); }
BannerCarousel.tsx
{carouselItems.map((item, index) => { return ( <BannerCarouselItem key={item.title + index} item={item} speed={speed} active={index === currentIndex} transition={transitionEnabled} /> ); })}
翻译文件结构(public/locales/[locale]/home.json)
{ "banner-carousel": [ { "title": "title", "subtitle": "text", "imgUrl": "/main_carousel/action.jpg", "imgUrlMobile": "/main_carousel/action_mobile.jpg" } ] }
已尝试的解决方案
- 用
useEffect添加布尔标记,延迟轮播组件的渲染时机 - 在
getServerSideProps中通过i18n.t()单独加载翻译数组,作为props传递给轮播组件
以上两种方法均未解决问题,请问为什么映射翻译数组的方式会导致SSR渲染不匹配?我是Next.js和服务端开发新手,可能问题出在未注意到的细节上,恳请提供解决思路。
内容的提问来源于stack exchange,提问作者brainpostman
相关产品推荐
相关产品推荐

