【问题标题】:Dynamically change locale without redux不使用 redux 动态更改语言环境
【发布时间】:2018-09-29 01:31:37
【问题描述】:

我想知道是否可以在不使用 redux 的情况下动态更改语言环境并让应用重新呈现。

ReactDOM.render(
<IntlProvider locale={window.locale} messages={window.messages} >
    <Router history={history}>
        <App /> 
    </Router>
</IntlProvider>,
document.getElementById('root'));
registerServiceWorker();

【问题讨论】:

    标签: javascript reactjs internationalization react-intl


    【解决方案1】:

    您可以在IntlProvider 上方拥有容器组件,并将语言环境作为道具传递。但我想传递组件树会非常乏味:

    class Container extends React.Component {
      state: {
        locale: window.locale
      }
    
      changeLocale = (locale) => this.setState({ locale })
    
      render() {
        return (
          <IntlProvider locale={this.state.locale} messages={window.messages} >
            <Router history={history}>
              <App changeLocale={this.changeLocale} /> 
            </Router>
          </IntlProvider>,
        )
      }
    }
    

    【讨论】:

    • 是的,这是个好主意,但经过一些研究,我决定继续使用 Redux。我一直在避免它,因为我的老师不让我,但现在他给了我使用 Redux 的绿灯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2020-04-22
    相关资源
    最近更新 更多