我是本機反應的新手,我嘗試使用 AsyncStorage 存盤所選語言,但我遇到了一個我不明白的問題。
import * as Localization from 'expo-localization';
import i18n from 'i18n-js';
import { en, fr } from '../i18n/supportedLanguages';
import AsyncStorage from '@react-native-async-storage/async-storage';
i18n.fallbacks = true;
i18n.translations = { en, fr };
i18n.locale = Localization.locale;
const storeData = async () => {
try {
const exist = await AsyncStorage.getItem('selectedLanguage');
console.log('a',exist, 'a');
if (exist == null) {
await AsyncStorage.setItem(
'selectedLanguage',
i18n.locale
);
}
} catch (error) {
}
};
const getData = async () => {
try {
const value = await AsyncStorage.getItem('selectedLanguage');
if (value !== null) {
console.log('b',value,'b');
return value;
}
} catch (error) {
}
};
storeData();
const thing = getData();
console.log('c',thing,'c');
結果是:
c Promise {
"_U": 0,
"_V": 0,
"_W": null,
"_X": null,
} c
a fr-FR a
b fr-FR b
我想知道為什么'c'console 首先出現,為什么它會回傳?請幫忙!
uj5u.com熱心網友回復:
因為,getData()是一個異步函式。
嘗試這個
getData().then(thing => console.log('c', thing, 'c'))
代替
const thing = getData();
console.log('c',thing,'c');
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/334685.html
