尽管打印正确,但为什么我的函数返回 undefined
Why is my function returning undefined despite printing out correctly
代码
函数返回
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 个小时来解决这个问题,有人可以帮我解决一下吗?如果可能的话,请深入解释问题所在,以便我可以将其记录在某个地方。谢谢
您的 totalBreaks
在您设置之前已被阅读。就这么简单:
const result = {};
const {val} = result;
result.val = 'foo';
console.log(val); // you will still get undefined.
这与异步无关
代码
函数返回
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 个小时来解决这个问题,有人可以帮我解决一下吗?如果可能的话,请深入解释问题所在,以便我可以将其记录在某个地方。谢谢
您的 totalBreaks
在您设置之前已被阅读。就这么简单:
const result = {};
const {val} = result;
result.val = 'foo';
console.log(val); // you will still get undefined.
这与异步无关