fix: 修复前端语言切换时后端 header 未更新的问题
- 统一 localStorage key:LanguageSwitcher 同时保存到 i18n_language 和 i18nextLng - 优化 API 请求拦截器:添加 getCurrentLanguage() 函数,优先从 localStorage 读取最新语言设置 - 支持兼容性:同时读取 i18n_language 和 i18nextLng(i18next 默认 key) - 规范化语言格式:确保返回正确的语言代码(zh-CN, zh-TW, en)
This commit is contained in:
@@ -22,7 +22,9 @@ const LanguageSwitcher: React.FC = () => {
|
||||
const handleChange = async (value: string) => {
|
||||
setCurrentLang(value)
|
||||
await i18n.changeLanguage(value)
|
||||
// 保存到 localStorage
|
||||
// 保存到 localStorage(统一使用 i18n_language)
|
||||
localStorage.setItem('i18n_language', value)
|
||||
// 同时保存到 i18nextLng(i18next 默认使用的 key,用于兼容)
|
||||
localStorage.setItem('i18nextLng', value)
|
||||
// 刷新页面以应用 Ant Design 的 locale 和所有翻译
|
||||
window.location.reload()
|
||||
|
||||
@@ -27,6 +27,35 @@ const apiClient: AxiosInstance = axios.create({
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* 获取当前语言设置(优先从 localStorage 读取,确保获取最新值)
|
||||
*/
|
||||
const getCurrentLanguage = (): string => {
|
||||
// 优先从 localStorage 读取用户设置的语言(统一使用 i18n_language)
|
||||
let savedLanguage = localStorage.getItem('i18n_language')
|
||||
|
||||
// 如果 i18n_language 不存在,尝试从 i18nextLng 读取(i18next 默认使用的 key)
|
||||
if (!savedLanguage) {
|
||||
savedLanguage = localStorage.getItem('i18nextLng')
|
||||
}
|
||||
|
||||
// 如果设置了具体语言,使用设置的语言
|
||||
if (savedLanguage && savedLanguage !== 'auto' && ['zh-CN', 'zh-TW', 'en'].includes(savedLanguage)) {
|
||||
return savedLanguage
|
||||
}
|
||||
|
||||
// 如果设置为 auto 或未设置,使用 i18n 的当前语言
|
||||
// 如果 i18n.language 也没有,使用默认值 'en'
|
||||
const currentLang = i18n.language || 'en'
|
||||
|
||||
// 确保返回的语言格式正确(移除可能的区域代码,如 'en-US' -> 'en')
|
||||
if (currentLang.startsWith('zh-CN')) return 'zh-CN'
|
||||
if (currentLang.startsWith('zh-TW') || currentLang.startsWith('zh-HK')) return 'zh-TW'
|
||||
if (currentLang.startsWith('en')) return 'en'
|
||||
|
||||
return 'en'
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求拦截器
|
||||
*/
|
||||
@@ -37,8 +66,8 @@ apiClient.interceptors.request.use(
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
// 添加语言 Header
|
||||
const language = i18n.language || 'en'
|
||||
// 添加语言 Header(每次请求都获取最新值)
|
||||
const language = getCurrentLanguage()
|
||||
config.headers['X-Language'] = language
|
||||
return config
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user