如何实现语言切换按钮,并将用户选择持久化到 cookie 或 localStorage?

解读

该问题考察候选人对 Next.js 国际化(i18n)机制的理解,以及在实际开发中处理用户偏好持久化的能力。需要结合 Next.js 的文件路由系统、客户端状态管理和持久化存储方案,实现动态语言切换功能。重点在于如何在不破坏 SEO 和 SSR 的前提下,完成语言状态的保存与恢复。

知识点

  1. Next.js i18n 配置原理
  2. 动态路由与语言参数绑定
  3. 客户端状态管理(useRouter)
  4. localStorage 与 cookie 的存储机制
  5. 语言切换时的页面重定向逻辑
  6. 多语言资源文件管理策略
  7. SSR 环境下的状态同步问题

答案

实现语言切换需要以下步骤:

  1. 配置 i18n 在 next.config.js 中设置:
module.exports = {
  i18n: {
    locales: ['zh', 'en'],
    defaultLocale: 'zh',
    localeDetection: false
  }
}
  1. 创建语言切换组件
// components/LanguageSwitcher.js
import { useRouter } from 'next/router';

export default function LanguageSwitcher() {
  const router = useRouter();
  const { locale } = router;
  
  const changeLanguage = (newLocale) => {
    // 使用 localStorage 持久化
    localStorage.setItem('preferredLanguage', newLocale);
    
    // 使用 cookie 持久化
    // document.cookie = `preferredLanguage=${newLocale}; path=/; max-age=3600000`;
    
    router.push({
      pathname: router.pathname,
      query: router.query,
      locale: newLocale
    });
  };

  return (
    <button onClick={() => changeLanguage('zh')}>
      中文
    </button>
    <button onClick={() => changeLanguage('en')}>
      English
    </button>
  );
}
  1. 页面加载时读取存储 在页面组件中使用:
// pages/_app.js
import { useEffect } from 'react';
import { appWithTranslation } from 'next-i18next';

export default appWithTranslation((props) => {
  useEffect(() => {
    // 从 localStorage 读取
    const savedLocale = localStorage.getItem('preferredLanguage') || 'zh';
    
    // 从 cookie 读取
    // const savedLocale = document.cookie
    //   .split('; ')
    //   .find(row => row.startsWith('preferredLanguage='))?.split('=')[1] || 'zh';
    
    // 设置默认语言
    // 需要配合 next-i18next 的 useTranslation 钩子
    // 通常由 appWithTranslation 处理
  }, []);
  
  return <div>{props.children}</div>;
});
  1. 语言资源文件管理
// public/locales/zh.json
{
  "common": {
    "hello": "你好"
  }
}

// public/locales/en.json
{
  "common": {
    "hello": "Hello"
  }
}

拓展思考

  1. 需要考虑 SSR 与 CSR 的状态同步问题,建议使用 next-i18next 提供的 useTranslation 钩子进行状态管理
  2. 语言切换时应避免重复加载翻译文件,可通过动态导入实现按需加载:
import dynamic from 'next/dynamic';
const DynamicTranslation = dynamic(() => import('@/components/Translation'), {
  ssr: false
});
  1. 安全性方面,使用 cookie 时需注意 HttpOnly 和 Secure 标志,建议结合 next-i18next 的 locale 配置进行校验
  2. 对于大型项目,可考虑使用 i18next 的 backend 选项实现多语言资源的集中管理
  3. 需要处理浏览器语言检测与用户选择的优先级,建议在 next.config.js 中设置 localeDetection: false 以避免自动检测
  4. 语言切换后应触发页面重新渲染,可通过 router.replace() 或 router.push() 实现
  5. 考虑使用 TypeScript 进行类型校验,确保语言值与配置的 locales 保持一致