React Native AsyncStorage在渲染后获取数据

skl*_*est 34 react-native

我正在使用AsyncStoragein ComponentWillMount来获取本地存储accessToken,但它在render()函数运行后返回promise .如何render()在承诺完成之前等待?谢谢.

jas*_*ino 64

isLoading据我所知,你不能等待.我在我正在处理的应用程序中完成的是添加一个加载屏幕,直到AsyncStorage的承诺解决.请参阅以下示例:

//
// With class component syntax
//

import React from 'react';
import {
  AsyncStorage,
  View,
  Text
} from 'react-native';

class Screen extends React.Component {

  state = {
    isLoading: true
  };

  componentDidMount() {
    AsyncStorage.getItem('accessToken').then((token) => {
      this.setState({
        isLoading: false
      });
    });
  },

  render() {
    if (this.state.isLoading) {
      return <View><Text>Loading...</Text></View>;
    }
    // this is the content you want to show after the promise has resolved
    return <View/>;
  }

}
Run Code Online (Sandbox Code Playgroud)

isLoading在状态对象上设置属性将导致重新呈现,然后您可以显示依赖于accessToken的内容.

另外,我写了一个名为react-native-simple-store的小库,它简化了AsyncStorage中的数据管理.希望你觉得它有用.

  • 这仍然适用于最新版本的React Native吗?我已经完全实现了这段代码,但它只会永远停留在"正在加载......"上.如果我在渲染上运行控制台登录以显示isLoading(没有if方法),则返回false,然后返回true,理论上它应该正常工作.但是如果启用了if方法,它将永远停留在"正在加载",并且日志仅返回false. (5认同)

Nim*_*ush 9

基于react-native doc,您可以执行以下操作:

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 (
        <View><Text>Loading...</Text></View>
      );
    }
    return (
      <View><Text>Main Page</Text></View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)