将异步存储与useState一起使用会给我带来一个问题,我需要按两次才能更新值



我正在使用带useState的异步存储,遇到一个小问题,我想添加警报,当用户按ok时,我想在异步存储中保存一个字符串,但问题是,用户需要按两次,因为异步存储存储旧的useState值,如何解决该问题,

这是我的代码,我会尽我所能用我的低英语水平更好地描述它,

1-异步存储

import AsyncStorage from '@react-native-async-storage/async-storage';
export default function App() {
const [wantNotification, setWantNotification] = useState('NO');
// Async Storage Saving Yes for Notifications
const storeNotificationAsync = async wantNotification => {
try {
await AsyncStorage.setItem('wantNotification', wantNotification);
setWantNotification('YES'); // I Need to press twice becuase when I press the first time Async Storage store "No"
} catch (e) {
console.log(e);
}
};
}

2-AsyncStorage getItem

const getNotificationAsync = async () => {
try {
const value = await AsyncStorage.getItem('wantNotification');
if (value !== null) {
console.log(value);
// It Logs "NO" If i press one time In the Alert
}
} catch (e) {}
};  

3-警报

const createAlert = () =>
Alert.alert(
'Notifications',
'Do You Want Notifications',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'OK',
onPress: async () => {
await storeNotificationAsync(wantNotification);
await console.log(wantNotification);

},
},
],
{cancelable: false});

第一次保存时,您的状态设置为"否":

const storeNotificationAsync = async wantNotification => {
try {
await AsyncStorage.setItem('wantNotification', wantNotification);
setWantNotification('YES'); // I Need to press twice becuase when I press the first time Async Storage store "No"
} catch (e) {
console.log(e);
}
};

从这里开始,它被称为:

onPress: async () => {
await storeNotificationAsync(wantNotification);
await console.log(wantNotification);
},

考虑到你的设置,你应该这样做:

const storeYesNotificationAsync = async () => {
const yes = 'YES';
try {
await AsyncStorage.setItem('wantNotification', yes);
setWantNotification(yes); // I Need to press twice becuase when I press the first time Async Storage store "No"
} catch (e) {
console.log(e);
}
};

调用应该是这样的:

onPress: () => storeYesNotificationAsync()

相关内容

最新更新