Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

reactjs - missing translation in react native expo i18n

so in my app I need to have my text in Spanish and English depending on how it's config on the cellphone itself. Anyway, after a lot of research, every try that I did come up with the same conclusion that is [missing 'en.Messages' translation]. Can someone tell me what am I missing or doing wrong?

APP.JS

  import { loadLocale } from "./i18n";

  const init = async () => {
    await loadLocale();
  };

  useEffect(() => {
    init();
  }, []);

i18n.js

import * as Localization from "expo-localization";
import i18n from "i18n-js";

i18n.defaultLocale = "en";
i18n.locale = "en";
i18n.fallbacks = true;

export const loadLocale = async () => {
  for (const locale of Localization.locales) {
    if (i18n.translations[locale.languageCode] !== null) {
      i18n.locale = locale.languageCode;
      switch (locale.languageCode) {
        case "en":
          import("./translations/en.json").then((en) => {
            i18n.translations = { en };
          });
          break;
        default:
        case "es":
          import("./translations/es.json").then((es) => {
            i18n.translations = { es };
          });
          break;
      }
      break;
    }
  }
};

export default i18n;

translations folder

inside the translations folder are 2 files call en.json / es.json
{
    "Messages": "Messages!",
}

Messages.js

import i18n from "../i18n";

<Text>{i18n.t("Messages")}</Text>
question from:https://stackoverflow.com/questions/65648389/missing-translation-in-react-native-expo-i18n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try setting defaultLocale before you load locale.

import { loadLocale } from "./i18n";

     i18n.defaultLocale = "en";
     i18n.locale = "en";
     i18n.fallbacks = true;

  const init = async () => {
    await loadLocale();
  };

  useEffect(() => {
    init();
  }, []);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...