嘿,我一直都在使用react-natives-community异步存储,我无法终生获得状态保存,而且我不太确定为什么。来自await变量的第一个console.log返回正确的信息,但是当我设置状态时,第二个console.log返回null并且我不确定发生了什么
const [userEmail, setUserEmail] = useState<string | null>(null);
const getEmail = await AsyncStorage.getItem('email')
console.log(getEmail + 'first')
setUserEmail(getEmail);
console.log(userEmail + 'second')
我做了这个自定义的钩子,但还是没有运气
const useGetAsyncStorage = (AsyncStorageItem: string): string => {
try {
const [data, setData] = useState<string | null>(null);
useEffect(() => {
const fetchAsyncStorage = async () => {
const AsyncStorageData = await AsyncStorage.getItem(AsyncStorageItem);
console.log(AsyncStorageData)
setData(AsyncStorageData);
};
fetchAsyncStorage();
}, [AsyncStorageItem]);
return data as string
} catch (error) {
return error
}
};
答案 0 :(得分:0)
问题是状态更新是异步的。您最终将看到电子邮件的null最初是什么。如果要查看更改,则应在useEffect()钩子中进行console.log