React Native AsyncStorage 在渲染后获取数据 [英] React Native AsyncStorage fetches data after rendering

查看:68
本文介绍了React Native AsyncStorage 在渲染后获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using AsyncStorage in ComponentWillMount to get locally stored accessToken, but it is returning the promise after render() function has run. How can I make render() wait until promise is completed? Thank you.

推荐答案

据我所知,你不能让组件等待渲染.我在我正在开发的应用程序中所做的是添加一个加载屏幕,直到 AsyncStorage 的承诺得到解决.请参阅以下示例:

You can't make a component wait to render, as far as I know. What I've done in the app I'm working on is to add a loading screen until that promise from AsyncStorage resolves. See the examples below:

//
// 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/>;
  }

}

//
// With function component syntax and hooks (preferred)
//

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

const Screen () => {

  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    AsyncStorage.getItem('accessToken').then((token) => {
      setIsLoading(false);
    });
  }, [])

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

}

在 state 中设置 isLoading 属性将导致重新渲染,然后您可以显示依赖于 accessToken 的内容.

Setting the isLoading property in state will cause a re-render and then you can show the content that relies on the accessToken.

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

On a side note, I've written a little library called react-native-simple-store that simplifies managing data in AsyncStorage. Hope you find it useful.

这篇关于React Native AsyncStorage 在渲染后获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆