【问题标题】:React native how to store language in AsyncStorage and change the app language?React Native 如何在 AsyncStorage 中存储语言并更改应用程序语言?
【发布时间】:2021-09-28 04:57:14
【问题描述】:

我正在尝试制作一个简单的 React Native 应用程序。一开始有一种默认语言,有一个按钮,通过单击它来更改语言并使用新语言重新加载应用程序。这个想法是将该语言存储在 AsyncStorage (@react-native-async-storage/async-storage) 中。

这是我的 cache.js:

import AsyncStorage from '@react-native-async-storage/async-storage';
import moment from 'moment';

const prefix = 'cache';
const expiryInMinutes = 5;

const store = async (key, value) => {
    try {
        const item = {
            value,
            timestamp: Date.now()
        }
        await AsyncStorage.setItem(prefix + key, JSON.stringify(item));
    } catch (error) {
        // console.log(error);
    }
}

const get = async (key) => {
    try {
        const value = await AsyncStorage.getItem(prefix + key);
        const item = JSON.parse(value);

        if(!item) return null;
        if(isExpired(item)) {
            await AsyncStorage.removeItem(prefix + key);
            return null;
        }
        return item.value;
    } catch(error) {
        // console.log(error);
    }
}

const isExpired = (item) => {
    const now = moment(Date.now());
    const storedTime = item.timestamp;
    return now.diff(storedTime, 'minutes') > expiryInMinutes;
}

export default { store, get };

这是我的 App.js:

import React from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';
import * as Updates from 'expo-updates';
import i18n from './app/locales/locales';
import cache from './app/utility/cache';

export default function App() {
  // When a value is missing from a language it'll fallback to another language with the key present.
  i18n.fallbacks = true;
  i18n.locale = 'de';
  cache.get('lang').then(function(result) {
    if(result) {
      i18n.locale = result;
      // console.log("New lang " + result);
    }
  });
  const handleRestart = async () => {
    // console.log("Storing lang: ");
    // console.log("Reseting lang: ");
    cache.store("lang", 'en');
    // console.log(cache.get('lang'));
    // console.log("Hmm");
    // console.log(i18n.locale);
    await Updates.reloadAsync();
  }

  return (
    <View style={styles.container}>
      <Text>{i18n.t('hello')}</Text>
      <Button title="Restart" onPress={handleRestart} />
    </View>
  );
}

它以德语开始,当我按下按钮时它会存储英语,但不会更改应用程序语言。我做错了什么?

【问题讨论】:

标签: javascript react-native


【解决方案1】:

我认为 UI 没有得到更新,因为只有在 props 或 state 发生变化时才会重新渲染。由于这些都没有更改,因此您不会在 UI 上看到任何更新。

试试这样的

const [lang, setLang] = React.useState(langValueFromStorage);
const handleRestart = () => {
 
cache.get('lang').then(function(result) {
    if(result) {
      i18n.locale = result;
      setLang(result)
    }
  });
}

【讨论】:

    【解决方案2】:
    1. 我找到了一个解决方案,虽然它看起来有点老套。 i18n.js
    import AsyncStorage from '@react-native-async-storage/async-storage';
    import i18n from 'i18next';
    import {initReactI18next} from 'react-i18next';
    import en from './src/localization/en/en.json';
    import uz from './src/localization/uz/uz.json';
    
    const resources = {
      en: {
        translation: en,
      },
      uz: {
        translation: uz,
      },
    };
    
    const getDefaultLang = async () => {
      const storedLang = await AsyncStorage.getItem('lang');
    
      return i18n
        .use(initReactI18next) 
        .init({
          resources,
          lng: storedLang ? storedLang : 'uz', 
    
          interpolation: {
            escapeValue: false, 
          },
    
          fallbackLng: ['uz', 'en'],
        });
    };
    
    export default getDefaultLang();
    
    1. 还有一个plugin 用于检测我刚刚发现的异步存储中的语言

    【讨论】:

      猜你喜欢
      • 2016-06-17
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      相关资源
      最近更新 更多