将 Async Storage 与 useState 一起使用时遇到问题,我需要按两次才能更新值

Using Async Storage with useState cusses me an issue, I need to press twice to update the value

我正在使用带有 useState 的异步存储,但有一个小问题,我想添加警报,当用户按确定时,我想在异步存储中保存一个字符串,但问题是,用户需要按两次,因为异步存储存储 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});

您的状态设置为 'NO' 第一次保存:

  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()