如果用户未登录,我将尝试呈现 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/