【问题标题】:I18Next - wait for Redux store to be set with local dataI18Next - 等待使用本地数据设置 Redux 存储
【发布时间】:2021-05-27 10:54:31
【问题描述】:

我希望 i18next 等待 redux 存储准备好。我将用户选择的语言存储在商店中,使用来自redux-persist 的持久化器在应用程序启动时对其进行补充。我尝试从商店设置语言:

// ...
import store from '../redux';
// ...
const lng = store.getState().user.language
  ? store.getState().user.language
  : Localization.locale.slice(0, 2);

i18next
  // .use(languageDetector)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    debug: true,
    resources,
    lng,
  });

但此时商店仍处于初始状态,尚未重新水化。有没有办法做到这一点?

【问题讨论】:

标签: react-native redux i18next react-i18next redux-persist


【解决方案1】:

所以PersistGate 可以实现一个onBeforeLift 方法,等待它解决后再解除“加载”状态。

const onBeforeLift = async () => {
  await initI18Next();
};

export default function App(): React.ReactElement {
  return (
    <Provider store={store}>
      <PersistGate
        loading={<SplashScreen />}
        persistor={persistor}
        onBeforeLift={onBeforeLift}
      >
        <StatusBar hidden />
        <MainNavigation />
      </PersistGate>
    </Provider>
  );
}

在i18n.ts:

const resources = {
  en: { translation: en },
  fr: { translation: fr },
  he: { translation: he },
};

export const init = () => {
  const lng = store.getState().user.language
    ? store.getState().user.language
    : Localization.locale.slice(0, 2);

  return (
    i18next
      .use(initReactI18next)
      .init({
        fallbackLng: 'en',
        debug: true,
        resources,
        lng,
      })
  );
};

export default i18next;

【讨论】:

  • 非常感谢!!!你节省了我的时间。
猜你喜欢
  • 1970-01-01
  • 2019-05-23
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 2016-04-09
  • 2019-01-19
相关资源
最近更新 更多