首页 文章

React Native AsyncStorage在渲染后获取数据

提问于
浏览
28

我在 ComponentWillMount 中使用 AsyncStorage 来获取本地存储 accessToken ,但它在 render() 函数运行后返回了承诺 . 如何让 render() 等到承诺完成?谢谢 .

3 回答

  • -5

    据我所知,你不能让 render 等一下 . 我正在做的是添加一个加载屏幕,直到AsyncStorage的承诺解决 . 请参阅以下示例:

    import React, {
      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/>;
      }
    
    }
    

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

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

  • 52

    基于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>
        );
      }
    }
    
  • 8

    React-native基于Javascript,它不支持阻塞功能 . 这也是有道理的,因为我们不希望UI卡住或看起来没有响应 . 你可以做的是在渲染功能中处理它 . 即当您从AsyncStorage获取信息时,让加载屏幕重新呈现

相关问题