2017-10-16 89 views
0

您好我想檢查,如果沒有導航登錄用戶的用戶登錄屏幕,但應用程序第一次打開時用戶將導航到登錄屏幕 如何運行只有一個屏幕加載反應本機屏幕加載功能

代碼
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

將您的代碼移入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() { 

} 
+0

我登錄了componentWillReceiveProps控制檯。但從來沒有觸發 –

+0

我以爲你正在使用REDX。 shouldComponentUpdate將爲你工作。我添加了一些代碼示例 – SNT

+0

但反應導航選項卡更改不重新安裝組件 –

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