【发布时间】:2021-12-28 23:28:27
【问题描述】:
代码
函数返回
async getData(key, setHook) {
try {
await AsyncStorage.getItem(key).then((response) => {
console.log("getData response: " + response); // prints out correctly
setHook(response); // sets my hook as undefined?
})
} catch(e) {
console.log("AsyncStorage getData: error: " + e);
}
}
接收函数
const key = 'key';
const Home = ( {navigation} ) => {
...
const [totalBreaks, setTotalBreaks] = useState('0'); // the hook I use in the above function
// on mount setCounter
useEffect(() => {
setCounter();
}, []);
async function setCounter () {
await asyncStorageInterface.getData(key, setTotalBreaks);
console.log("total breaks: " + totalBreaks); // returns undefined on mount... when it shouldn't
if(totalBreaks === null || totalBreaks === undefined) {
await asyncStorageInterface.storeData(key, '0');
await asyncStorageInterface.getData(key, setTotalBreaks);
}
console.log("total breaks: " + totalBreaks);
}
问题
我不知道问题是什么...我花了将近 6 个小时试图解决这个问题,有人可以帮助我吗?如果可能的话,请深入解释问题所在,以便我可以在某处记录它。谢谢。
【问题讨论】:
-
注意:使用
then和await是一种反模式。 -
试试这个:
const result = await AsyncStorage.getItem(key); setHook(result);
标签: javascript asynchronous async-await