开发者问题收集

TypeError:无法读取 react-localize-redux 中未定义的属性“语言”

2019-02-22
3453

我试图将 react-localize-redux 实现到我的应用程序中。但是我得到了以下错误

TypeError: Cannot read property 'languages' of undefined

这来自 node_modules/react-localize-redux/es/localize.js:249

我的代码实现如下。

let store = createStore(combineReducers({icm: icmReducer, locale: locale}));

ReactDOM.render(
<Provider store={store}>
    <LocalizeProvider store={store}>
        <App/>
    </LocalizeProvider>
</Provider>,
document.getElementById('root'));

App.js

class App extends React.Component {

constructor(props) {
    super(props);
    this.props.initialize({
        languages: [
            {name: "English", code: "en"},
            {name: "French", code: "fr"}
        ],
        translation: globalTranslations,
        options: {renderToStaticMarkup}
    });
}

render() {
    return (
        <div className="App container">
            <Header/>
            <InvoiceAudit/>
        </div>
    );
  }
}

export default withLocalize(App);

global.json

{
 "welcome": {
"greeting": [
  "Hello",
  "Bonjour",
  "Hola"
],
"farewell": [
  "Goodbye",
  "Au revoir",
  "Adiós"
  ]
 }
}

错误

在此处输入图片描述

3个回答

我找到了解决方案。当我们将 Reducer 与 localizeReducer 结合使用时,我们需要提供 localize 作为名称。这是必须的,否则它将不起作用。

import {LocalizeProvider, localizeReducer} from 'react-localize-redux';

let store = createStore(combineReducers({icm: IcmWebReducer, localize: localizeReducer}));

这里提到了这一点: https://ryandrewjohnson.github.io/react-localize-redux-docs/#what-if-i-want-to-use-redux

Pubudu Jayasanka
2019-02-22

看起来您初始化了 2 种语言,但有 3 种翻译。您应该将西班牙语添加到初始化程序中:

languages: [
  {name: "English", code: "en"},
  {name: "French", code: "fr"},
  {name: "Spanish", code: "es"}
],

(只是猜测这是问题所在)

Austin Greco
2019-02-22

如果您希望在商店中使用不同名称或不同路径的 localize ,只需使用 getState 属性即可。

(TypeScript)

<LocalizeProvider
  store={store}
  getState={(state: AppState) => state.user.locale}
>
//...
</LocalizeProvider>

应用程序状态的结果: state.png

stpoa
2020-02-24