无法在React Native应用程序启动时读取AsyncStorage值

kb5ga3dv  于 2022-12-04  发布在  React
关注(0)|答案(2)|浏览(169)

下面的代码用于创建Redux存储,并使用AsyncStorage通过检查authToken是否存在来检查用户是否登录。

import {createStore} from 'redux';
import {persistStore} from 'redux-persist';

async function getAuthToken() {
  return await AsyncStorage.getItem('authToken');
}

export function createStore(onCompletion:() => void):any {
  ...

  const store = createStore(
    reducer,
    {
      auth: {
        authenticated: !!getAuthToken()
      }
    },
    enhancer);

  persistStore(store, {
    storage: AsyncStorage,
  },
  onCompletion);
}

商店的创建:

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      store: createStore(...),
    };
  }

  render() {
    return (
      <Provider store={this.state.store}>
        <AppNavigator />
      </Provider>
    );
  }
}

authToken值在用户登录后被正确设置,并在用户注销后被删除。但authToken在应用重新启动后不会被持久化。第一次调用getAuthToken总是从AsyncStorage返回这个垃圾值:
{ _45:0,_81:0,_65:空,_54:空值}
为什么会这样?

wdebmtf2

wdebmtf21#

现在您要从AsyncStorage返回一个promise,您需要返回令牌值。

async function getAuthToken() {
  return await AsyncStorage.getItem('authToken').then((token) => token);
}
d8tt03nd

d8tt03nd2#

使用挂钩效果

import AsyncStorage from '@react-native-async-storage/async-storage';
import { useState, useEffect } from 'react';

export function App() {
  const [token, setToken] = useState<string>();
  useEffect(()=>{
    (async function() {
      setToken(await AsyncStorage.getItem());
      await SplashScreen.hideAsync();
    })();
  },[]);
  if (token) {
    return (<View><Text>{token}</Text></View>);
  } else {
    return null;
  }
}

相关问题