React Native-localize翻译缺失问题排查(翻译文件已存在)
I see you're running into an issue where translations aren't showing up even though your translation files exist. Let's break down the potential problems in your code and fix them step by step.
1. Critical Issue: Function Component Misusing Class Component Syntax
Your App component is a function component, but you're using class component patterns that won't work here:
handleLocalizationChange = () => {}is class component syntax; in function components, you need to define functions directly or useuseCallback.this.forceUpdate()doesn't exist in function components—you need to use a state hook to trigger re-renders when the language changes.setI18nConfigis a synchronous function, so chaining.then()will have no effect.
Fix for Component Re-rendering
Add a state variable to track language changes, and update it when the localization changes to trigger a re-render:
import { useState, useEffect, useCallback } from 'react'; const App = () => { // State to trigger re-render on language change const [locale, setLocale] = useState(''); const setI18nConfig = () => { const fallback = { languageTag: 'en', isRTL: false }; const { languageTag, isRTL } = RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) || fallback; translate.cache.clear(); I18nManager.forceRTL(isRTL); i18n.translations = { [languageTag]: translationGetters[languageTag]() }; i18n.locale = languageTag; // Update state to trigger re-render setLocale(languageTag); }; // Use useCallback to prevent unnecessary re-registrations const handleLocalizationChange = useCallback(() => { try { setI18nConfig(); } catch (error) { console.error(error); } }, []); useEffect(() => { setI18nConfig(); RNLocalize.addEventListener('change', handleLocalizationChange); return () => { RNLocalize.removeEventListener('change', handleLocalizationChange); }; }, [handleLocalizationChange]); return ( <ThemeProvider theme={ThemeRed}> <AppContainer /> </ThemeProvider> ); };
2. Verify Language Tag Matching
RNLocalize.findBestAvailableLanguage might return a language tag with a region code (like en-US or de-DE) instead of the simple en/de you have in translationGetters. While it should fall back to the base language, it's worth confirming which tag is being loaded.
Add a console log in setI18nConfig to check:
console.log('Loading language:', languageTag);
If you're getting region-specific tags, you can normalize them to the base language:
const normalizedTag = languageTag.split('-')[0]; // Then use normalizedTag instead of languageTag for translationGetters
3. Ensure i18n-js Fallbacks Are Enabled
Add this line when initializing i18n to ensure it falls back to your default language if a key is missing in the current locale:
i18n.fallbacks = true;
You can place this at the top of your file where you import i18n.
4. Check Memoization Logic
Your memoized translate function might be holding onto old translations if the cache isn't cleared properly. As a test, try removing the memoization temporarily to see if translations load correctly:
// Replace the memoized translate with a direct call const translate = (key, config) => i18n.t(key, config);
If this fixes the issue, adjust your memoization key to ensure it accounts for locale changes. For example, include the current locale in the memoization key:
const translate = memoize( (key, config, locale) => i18n.t(key, config), (key, config, locale) => `${locale}-${key}${config ? JSON.stringify(config) : ''}` );
Then pass the current locale when calling translate:
translate('welcome', null, i18n.locale)
5. Validate Translation File Paths and Content
Double-check:
- Your translation files (
./translations/en.json,./translations/de.json) are in the correct directory relative to your App component. - The
en.jsonandde.jsonfiles actually contain thewelcomekey:// en.json { "welcome": "Welcome!" }// de.json { "welcome": "Willkommen!" }
Try these fixes one by one, starting with the function component syntax issue—it's the most likely culprit here.
内容的提问来源于stack exchange,提问作者akano1

