React Native AsyncStorage fetches data after rendering

后端 未结 4 1835
一整个雨季
一整个雨季 2020-12-13 04:11

I am using AsyncStorage in ComponentWillMount to get locally stored accessToken, but it is returning the promise after render()<

4条回答
  •  温柔的废话
    2020-12-13 04:30

    Based on react-native doc, you can do something like this:

    import React, { Component } from 'react';
    import {
      View,
    } from 'react-native';
    
    let STORAGE_KEY = '@AsyncStorageExample:key';
    
    export default class MyApp extends Component {
    
      constructor(props) {
        super(props);
        this.state = {
          loaded: 'false',
        };
      }
    
      _setValue = async () => {
        try {
          await AsyncStorage.setItem(STORAGE_KEY, 'true');
        } catch (error) { // log the error
        }
      };
    
      _loadInitialState = async () => {
        try {
          let value = await AsyncStorage.getItem(STORAGE_KEY);
          if (value === 'true'){
            this.setState({loaded: 'true'});
          } else {
            this.setState({loaded: 'false'});
            this._setValue();
          }
        } catch (error) {
          this.setState({loaded: 'false'});
          this._setValue();
        }
      };
    
      componentWillMount() {
        this._loadInitialState().done();
      }
    
      render() {
        if (this.state.loaded === 'false') {
          return (
            Loading...
          );
        }
        return (
          Main Page
        );
      }
    }
    

提交回复
热议问题