嗨我想检查用户是否未登录导航用户登录屏幕但是当应用程序首次打开时,用户将导航到登录屏幕 如何在加载屏幕时运行代码
componentDidMount(){
AsyncStorage.getItem('islogin', (err, result) => {
console.log(result);
if (result!==true){
this.setState({login:false})
}
});
}
render() {
if(this.state.login==false){
const { navigate } = this.props.navigation;
navigate('profile',{ name: 'cat' })
}
}
答案 0 :(得分:0)
将您的代码移动到componentWillReceiveProps中。在导航上,您的组件将接收新的道具,并且将调用componentWillReceiveProps。所以在这里你可以检查AsyncStorage并导航用户。
componentDidMount(){
AsyncStorage.getItem('islogin', (err, result) => {
console.log(result);
if (result!==true){
this.setState({login:false})
}
});
}
shouldComponentUpdate(nextProps, nextStates) {
console.log(nextState)
if(nextState.login == false)
this.props.navigation.navigate('profile',{ name: 'cat' });
}
render() {
}
答案 1 :(得分:0)
我正在使用react-native-router-flux
进行路由,您可以按照代码中的描述执行条件状态。
import React, {Component} from 'react';
import {AsyncStorage} from 'react-native';
import {Scene, Router} from 'react-native-router-flux';
//Splash
import Splash from '../splashscreen_component';
//Home
import HomeScreen from '../home_component/HomeScreen';
//Login
import Signin from '../login_component/Signin';
var KEY = 'isLIn';
export default class AppRoutes extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
isLoading: true
};
}
componentWillMount() {
this._loadInitialState().done();
}
async _loadInitialState() {
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);
}
};
_loginscreen() {
return (
<Scene key="root" hideNavBar hideTabBar>
<Scene key="Signin" component={Signin} title="Signin" initial panHandlers={null}/>
<Scene key="Home" component={HomeScreen} title="Home" panHandlers={null}/>
</Scene>
);
}
_homescreen() {
return (
<Scene key="root" hideNavBar hideTabBar>
<Scene key="Home" component={HomeScreen} title="Home" initial panHandlers={null}/>
</Scene>
);
}
render() {
if (this.state.isLoading === true) {
return (<Splash/>);
} else {
if (this.state.isLoggedIn === true) {
return (
<Router>{this._homescreen()}</Router>
);
} else {
return (
<Router>{this._loginscreen()}</Router>
);
}
}
}
}