首页 文章

React-native:在从Storage获取数据之前呈现视图

提问于
浏览
1

我试图渲染Signin组件,如果用户没有登录,如果用户登录我正在尝试渲染Home组件 . 在登录组件集上存储'isLIn'至'true'在登出[来自主组件]时将存储'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>
    );
  }
}

我不知道为什么但是在Storage获得 Value 之前先查看渲染 . 根据react-native render() 的生命周期,只有 componentWillMount() 执行React_Doc后才会执行 .

我使用AsyncStorage来设置和删除存储,并使用React-Native-Router-Flux进行路由 .

我尝试过解决方案:

2 回答

  • 1

    由于您所做的是异步,因此无法告诉生命周期等待它 . 但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方法中,你可以放置一个占位符,直到你的asynctask结束

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

    在componentWillMount中调用setState不会触发重新呈现 . componentWillMount 在设置状态之后且在重新渲染视图之前运行 . 来自React Native Docs:

    "componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method." - https://facebook.github.io/react/docs/react-component.html#componentwillmount

    相反,你应该在 componentWillReceiveProps() 中调用 _loadInitialState

相关问题