代碼
函式回傳
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 個小時試圖解決這個問題,有人可以幫我嗎?如果可能的話,請深入解釋問題所在,以便我可以將其記錄在某處。謝謝。
uj5u.com熱心網友回復:
您totalBreaks在設定之前已閱讀。它很簡單:
const result = {};
const {val} = result;
result.val = 'foo';
console.log(val); // you will still get undefined.
這與異步無關
uj5u.com熱心網友回復:
你確定你收到的是 undefined 嗎?我認為你做的事情恰到好處,但問題是你相信console.log你最后擁有的東西。它列印未定義,但實際上它在設定它的實際值之前列印,這就是它未定義的原因。如果不是這種情況,請在評論中告訴我,我會盡快嘗試回答
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/396293.html
標籤:javascript 异步 异步等待
上一篇:減少多維陣列sumjs的錯誤
