You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用redux-react-native-i18n做本地化时遇TypeError错误求助

解决redux-react-native-i18n的TypeError: undefined is not an object (evaluating '_ref$i18n.currentLanguage')

这个错误大概率是因为你没有正确初始化i18n的状态,或者缺少了关键的初始化步骤,导致在访问currentLanguage时找不到对应的对象。我看你提供的代码里setDictionary的调用没写完,而且还有几个核心步骤没做,来一步步修复:

1. 补全store的初始化流程

首先要确保创建Loc实例并和store绑定,同时完整设置字典和默认语言。修改你的store/index.js代码如下:

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { i18nReducer, i18nActions, Loc } from 'redux-react-native-i18n';

// 合并你的其他reducers(如果有的话)
const rootReducers = {
  // 这里放你的其他reducer,比如user、cart等
  i18n: i18nReducer // 必须把i18n reducer加入根reducer
};

const store = createStore(
  rootReducers,
  {},
  compose(
    applyMiddleware(thunk)
  )
);

// 关键:创建Loc实例并绑定到store
const loc = new Loc(store);

// 你的字典定义不变
const dictionaries = {
  'en-US': {
    'oh': 'Order History',
  },
  'ko-KR': {
    'oh': '주문내역',
  },
  // 其他语言包...
};

// 完整分发设置字典的action
store.dispatch(i18nActions.setDictionary(dictionaries));

// 设置默认语言(可以改成从设备获取的语言,比如用react-native的I18nManager)
store.dispatch(i18nActions.setCurrentLanguage('en-US'));

// 导出store和loc,供组件使用
export { store, loc };

2. 在组件中正确使用翻译

之后在组件里,你可以通过loc实例来获取翻译内容,这样就不会出现状态未定义的问题了:

import { loc } from '../store';
import { Text } from 'react-native';

const OrderHistoryScreen = () => {
  // 用loc.t()方法获取翻译
  const orderHistoryText = loc.t('oh');

  return <Text>{orderHistoryText}</Text>;
};

export default OrderHistoryScreen;

错误原因分析

你之前的代码缺少了三个关键步骤:

  • 没有创建Loc实例并和store绑定,导致无法正确关联i18n状态
  • 没有完整执行setDictionary的action,字典没有被存入store
  • 没有设置初始语言,导致currentLanguage字段未初始化

这些步骤缺一不可,补全之后应该就能解决这个TypeError了。

内容的提问来源于stack exchange,提问作者merry-go-round

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:43:01