如何使用异步存储持久登录?

How to presist log in using Async Storage?

我正在尝试使用异步存储保存用户的登录状态,如下所示:在登录屏幕中:

function LoginScreen({navigation, route, props}) {
  **AsyncStorage.setItem('isLoggedIn', false);**
function loginTrial() {
    setIsLoggingIn(true);
    fetch('https://bazarti.com/api/login', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: username.toString(),
        password: password,
      }),
    })
      .then(res => {
        if (res.status === 200) {
          AsyncStorage.setItem('isLoggedIn', true);
          AsyncStorage.setItem('token', res.headers.get('token'));
          Alert.alert('Sign-in', 'Sign-in was successful'[
            {
              text: 'ok',
              onPress: () => navigation.navigate('UserProduct'),
            },
          ]);
        }
        if (!res.status === 200) {
          Alert.alert('Error', 'Invalid Creditentials', [
            {
              text: 'ok',
            },
          ]);
        }
      })
      .catch(error => console.log(error, 'error'));
  }

在应用程序导航 js 文件中:

function AppStackNavFunc() {
  let loggstat = AsyncStorage.getItem('isLoggedIn').then(res => res);
  if (loggstat === false) {
    return (
      <AppStackNav.Navigator>
        <AppStackNav.Screen
          name="LoginScreen"
          component={LoginScreen}
          options={LoginScreen.navigationoptions}
        />
        <AppStackNav.Screen
          name="UserProduct"
          component={UserProductScreen}
          options={UserProductScreen.navigationoptions}
        />
        <AppStackNav.Screen
          name="CreateNewProd"
          component={CreateNewProdScreen}
          options={CreateNewProdScreen.navigationoptions}
        />
        <AppStackNav.Screen
          name="OtherUsersProd"
          component={OtherUsersProdScreen}
          options={OtherUsersProdScreen.navigationoptions}
        />
      </AppStackNav.Navigator>
    );
  }
  if (loggstat === true) {
    return (
      <AppStackNav.Navigator>
        <AppStackNav.Screen
          name="UserProduct"
          component={UserProductScreen}
          options={UserProductScreen.navigationoptions}
        />
        <AppStackNav.Screen
          name="CreateNewProd"
          component={CreateNewProdScreen}
          options={CreateNewProdScreen.navigationoptions}
        />
        <AppStackNav.Screen
          name="OtherUsersProd"
          component={OtherUsersProdScreen}
          options={OtherUsersProdScreen.navigationoptions}
        />
      </AppStackNav.Navigator>
    );
  }
}
export default AppStackNavFunc;

问题显然是在应用程序导航 js 文件中,代码无法从 AsyncStorage 读取 isLoggedIn,而 AppNavStackFunc 什么也不做。如何正确实现 AsyncStorage?

AsyncStorage setItem 方法也将值作为字符串接收,但您传递的是布尔值,这就是不读取该值的原因。 这里勾选docs。 假定类型为字符串(对于值),因此您必须以相同的方式初始化和使用它