能否将Redux store作为next-i18next的翻译资源使用?
next-i18next 接入 Redux 动态翻译资源解决方案
核心逻辑说明
getServerSideProps 运行在服务端生命周期,和客户端运行的Redux store完全隔离,无法直接读取Redux内的数据。next-i18next底层依赖i18next,本身支持客户端动态更新翻译资源,只要联动Redux状态变化和i18next的资源更新接口即可实现需求。
实现步骤
- 保留服务端基础翻译注入
原有的getServerSideProps逻辑不变,通过serverSideTranslations注入首屏需要的基础翻译资源,保证页面首次加载正常。
export async function getServerSideProps({locale}) { return { props: { ...await serverSideTranslations(locale, ['common', 'slide1'], config), } } }
- 客户端联动Redux与i18next实例
在项目根组件(通常是_app.jsx/_app.tsx)中订阅Redux翻译状态的变化,调用i18next提供的资源更新方法同步翻译内容:
import { useTranslation } from 'next-i18next' import { useSelector } from 'react-redux' import { useEffect } from 'react' function MyApp({ Component, pageProps }) { const { i18n } = useTranslation() // 从Redux中取出当前语言对应的全量翻译资源,结构与translations.json完全一致 const reduxTranslations = useSelector(state => state.translations[i18n.language]) useEffect(() => { if (!reduxTranslations) return // 遍历所有命名空间覆盖更新翻译资源 Object.keys(reduxTranslations).forEach(namespace => { i18n.addResourceBundle( i18n.language, namespace, reduxTranslations[namespace], true, // 覆盖原有同key翻译 true // 深层合并资源 ) }) // 触发全局翻译重新渲染 i18n.reloadResources() }, [reduxTranslations, i18n]) return <Component {...pageProps} /> } export default MyApp
- 持久化翻译到translations.json
用户修改可编辑文本触发Redux action更新状态时,同步调用后端接口,把最新的翻译内容写入服务端的translations.json文件,避免页面刷新后修改丢失。
内容的提问来源于stack exchange,提问作者Ibrahim El-bana
相关产品推荐
相关产品推荐

