保持登录状态
现在大多数的app都有登录,并且第一次登录后,以后再打开应用就不会弹出登录页面了,
RN怎么实现这个呢?思考了好久想了好多思路,比如用RN存储,在登录的时候如果取到了用户名和密码就直接
登录,没取到就到登录页面,可是把网上的第三方存储组件看了个遍也难以实现。
后来灵光一闪,通过使用定时器,在启动屏延迟界面里获取用户名和密码直接登录
constructor(props) { super(props); this.state = { pwd:'', loginaccount:'', loaded: false, }; }
异步存储获取用户名和密码
componentWillMount(){ AsyncStorage.getItem(STORAGE_ACCOUNT) .then((value) => { console.log("loginaccount is "+value); if (value !== null){ this.setState({loginaccount:value}); } }) .catch((error) => { console.warn(error); }).done(); AsyncStorage.getItem(STORAGE_PWD) .then((value) => { console.log("pwd is "+value); if (value !== null){ this.setState({pwd:value}); } }) .catch((error) => { console.warn(error); }).done(); }
因为获取异步存储的用户名和密码。想在componentDidMount()方法里面直接
登录是行不通的,因为这个时候取不到用户名和密码,只能通过定时器,延时登录。
componentDidMount(){ this.timer=setTimeout( ()=>{ this.zhijielogin(); },1000 ); this.timer_two=setTimeout( ()=>{ this.setState({ loaded:true, }); },4000 ); }
renderLoadingView() { return ( <View style={{flex:1,justifyContent:"center",alignItems:'center'}}> <Image source={require('./img/abie1.png')} style={{width:deviceWidth,height:deviceHeight}} /> </View> ); }
render(){ if (!this.state.loaded) { return this.renderLoadingView(); } return( <View></View> )