【发布时间】: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>
);
}
它以德语开始,当我按下按钮时它会存储英语,但不会更改应用程序语言。我做错了什么?
【问题讨论】:
-
我写了一篇关于它的博客文章。它还使用i18n-js,时刻stefan-majiros.com/blog/…