javascript - React-native:在从存储中获取数据之前渲染 View

标签 javascript reactjs react-native redux asyncstorage

如果用户未登录,我将尝试呈现 Signin 组件;如果用户登录,我将尝试呈现 Home 组件。在登录组件上将存储'isLIn'设置为'true'注销[从主组件]设置存储< em>'isLIn' 到 'false' 并且每次 React-Native 应用程序打开时都会检查存储并将状态设置为存储的值。

请看代码:

import React, { Component } from 'react';
import { AsyncStorage } from 'react-native';
import { Scene, Router } from 'react-native-router-flux';
import Login from './login_component';
import Home from './home_component';

var KEY = 'isLIn';

export default class main extends Component {
  state = {
    isLoggedIn: false
  };

  componentWillMount() {
    this._loadInitialState().done();
  }

  _loadInitialState = async () => {
    try {
        let value = await AsyncStorage.getItem(KEY);
        if (value !== null && value === 'true') {
          this.setState({ isLoggedIn: true });
        } else {
          this.setState({ isLoggedIn: false });
        }
    } catch (error) {
      console.error('Error:AsyncStorage:', error.message);
    }
  };

  render() {
    const _isIn = (this.state.isLoggedIn===true) ? true : false;
    return (
        <Router>
          <Scene key="root" hideNavBar hideTabBar>
            <Scene key="Signin" component={Login} title="Signin" initial={!_isIn} />
            <Scene key="Home" component={Home} title="Home" initial={_isIn}/>
          </Scene>
        </Router>
    );
  }
}

我不知道为什么,但在存储获取值(value)之前先查看渲染。根据react-native的生命周期,render()仅在componentWillMount()之后执行,如React_Doc说。

我正在使用AsyncStorage设置并删除存储并使用 React-Native-Router-Flux用于路由。

我尝试过解决方案:

最佳答案

由于您正在做的事情是异步的,因此您无法告诉生命周期等待它。但是 React 提供了状态以及您可以使用的状态,例如

state = {
    isLoggedIn: false
    isLoading: true
  };

并在异步中设置状态

_loadInitialState = async () => {
    try {
        let value = await AsyncStorage.getItem(KEY);
        if (value !== null && value === 'true') {
          this.setState({ isLoggedIn: true, isLoading: false });
        } else {
          this.setState({ isLoggedIn: false, isLoading: false });
        }
    } catch (error) {
      console.error('Error:AsyncStorage:', error.message);
    }
  };

然后在渲染方法中您可以放置​​一个占位符,直到异步任务完成

render() {
 if(this.state.isLoading) return <div> Loading... </div>
 else return...
}

关于javascript - React-native:在从存储中获取数据之前渲染 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42982503/

相关文章:

javascript - 在 drupal 7 中分离内联 js

javascript - 使用字典映射 API 响应并创建对象数组,尝试删除重复项

javascript - 子组件的下一个js父路由组件

javascript - React-Native:状态已更改,但返回旧值

react-native - 由于 native 基础模块,Web Expo 无法编译

javascript - 如何从网络元素中获取定位器值?

javascript - 开始 0 不透明度和 onClick 设置不透明度为 100

react-native - Expo DevTools 显示发生意外错误

javascript - 为什么 string concat apply 不能按预期工作?

reactjs - 如何更新react-redux中的存储状态?