【问题标题】:Cannot read AsyncStorage value on React Native app startup在 React Native 应用程序启动时无法读取 AsyncStorage 值
【发布时间】:2017-01-23 03:06:37
【问题描述】:

我将 React Native 与 Redux 一起使用。以下代码用于创建 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: null, _54: null }

为什么会发生这种情况?

【问题讨论】:

    标签: ios react-native react-redux


    【解决方案1】:

    现在您从 AsyncStorage 返回一个承诺,您需要返回令牌值。试试:

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

    【讨论】:

    • 这对我不起作用,但我仍然得到相同的结果。我的理解是“等待”已经是同步的。我还使用相同的“等待”模式从 AsyncStorage 同步获取 authToken 并发送 HTTP 标头,这是有效的。
    猜你喜欢
    • 1970-01-01
    • 2017-06-30
    • 2017-01-05
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多