javascript - 加载时的路由不适用于我的 React native 应用程序

标签 javascript android reactjs react-native

我正在开发一个包含使用 firebase 的登录系统的 React Native 项目。登录系统工作正常。我还设法从 firebase 捕获了当前用户 ID。我尝试使用 asyncStorage 系统和当前用户 ID 设置一个“保持登录系统”。即使是异步存储也能正常工作。但我的问题是,如果 componentDidMount() 中的异步存储不为空,我会设置一个重定向到主页的方法。我为测试设置的警报系统在每次重新加载时都清楚地显示了正确存储在 asyncStorage 上的值。但是无法重定向到主页。

这是我的代码:

            import React from 'react';
            import { StyleSheet, 
                    Text, 
                    View, 
                    TouchableOpacity,
                    AsyncStorage,
                    } from 'react-native';
            import {RkTextInput, RkButton } from 'react-native-ui-kitten';
            import {Actions} from 'react-native-router-flux';

            import * as firebase from 'firebase';

            export default class Login extends React.Component {

            constructor(props){
                super(props)

                this.state=({
                email:'savadks1919@gmail.com',
                password:'123123',
                userId:'',
                errorMessage: null
                })
            }

            componentDidMount() {
                this._loadInitialState().done();
            }
                _loadInitialState = async () => {
                let value= await AsyncStorage.getItem('user');
                if (value !== null){
                    this.Home
                }
                }
                signup() {
                Actions.signup()
                }
                Home() {
                Actions.home()
                }

                handleLogin = (email, password) => {

                firebase.auth().signInWithEmailAndPassword(email, password).then(
                    this.Home, 
                    this.state=({userId:firebase.auth().currentUser.uid})
                ).catch(function(error) {
                    var errorCode = error.code;
                    var errorMessage = error.message;

                    if (errorCode === 'auth/wrong-password') {
                        alert('Wrong password.');
                    } else {
                        alert(errorMessage);         
                    }
                    console.log(error);
                });
                //--------------------------Async Test---------------------
                AsyncStorage.setItem('user', this.state.userId);
                //---------------------------------------------------------
                }

            render() {
                return (
                <View style={styles.container}>

                    <Text style={styles.titleText}>Taams</Text>
                    <Text style={styles.edition}>Developer's Edition</Text>
                    <Text style={styles.titleText}>Login.js</Text>
                    <Text>Alpha 0.0.0.1</Text>

                    {/*-----UserName Input-------*/}
                    <RkTextInput 
                        rkType= 'rounded' 
                        labelStyle= {{color: 'black', fontWeight: 'bold'}}
                        placeholder='UserName'
                        //--------------value Handler----------------//
                        onChangeText={(email) => this.setState({email})}

                        //---------------------------------//
                        selectionColor="#000000"
                        keyboardType="email-address"
                        onSubmitEditing={() => { this.password.focusInput(); }}
                        inputStyle={{
                        color: 'black',
                        fontWeight: 'bold',
                        }}/>


                    {/*-----Password-------*/}
                    <RkTextInput 
                        secureTextEntry={true}
                        rkType= 'rounded' 
                        placeholder='Password'
                        //--------------value Handler----------------//
                        onChangeText={(password) => this.setState({password})}

                        //---------------------------------//
                        ref={(input) => { this.password = input; }}
                        inputStyle={{
                        color: 'black',
                        fontWeight: 'bold',
                        }}/>

                    <RkButton onPress = {()=>this.handleLogin(this.state.email,this.state.password)}>
                    <Text style={styles.LoginButtonText}>Login</Text>
                    </RkButton>

                    <View style={styles.signupTextCont}>
                        <Text style={styles.signupText}>Don't have an account yet?</Text>
                        <TouchableOpacity onPress={this.signup}><Text style={styles.signinButton}>SignUp</Text></TouchableOpacity> 
                    </View>
                </View>

                );
            }
            }

            const styles = StyleSheet.create({
            container: {
                flex: 1,
                backgroundColor: '#fff',
                alignItems: 'center',
                justifyContent: 'center',
            },
            signupTextCont:{
                flexGrow: 0,
                alignItems:'center',
                justifyContent:'flex-end',
                marginVertical:15
            },
            signupText:{
                color:'rgba(64,64,64,0.6)',
                fontSize:16
            },
            signinButton:{
                color:'#000000',
                fontSize:16,
                fontWeight:'500'
            },
            titleText: {
                fontSize: 20,
                fontWeight: 'bold',
            },
            edition: {
                fontSize: 15,
                //fontWeight: 'bold',
            },
            TextInput: {
                width: 300,
                height:50,
                borderColor: 'grey',
                borderWidth: 1,
            },
            LoginButtonText: {
                fontSize: 20,
                fontWeight: 'bold',
                color: 'white',
                //alignItems: 'center'

            },
            });

我的路由器:

        import React, { Component } from 'react';
        import {Router, Stack, Scene} from 'react-native-router-flux';

        import SignUp  from './SignUp/SignUp';
        import Login   from './Login/Login';
        import Home    from "./Home/Home"
        import Profile from "./Profile/Profile"
        export default class Routes extends Component <{}>{
            render(){
                return(
                <Router>
                    <Stack key="root" hideNavBar={true}>
                    <Scene key="login" component={Login} title="Login" initial/>
                    <Scene key="signup" component={SignUp} title="Register" />
                    <Scene key="home" component={Home} title="Home" />
                    <Scene key="profile"component={Profile} title="profile"/> 
                    </Stack>
                </Router>
                )
            }
        }

最佳答案

改变调用函数的语法

if (value !== null){
   this.Home()
 }

关于javascript - 加载时的路由不适用于我的 React native 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54377595/

相关文章:

javascript - Webpack 在终端中运行时会给出 "error error: unknown option ' -p'"

javascript - 错误: Cannot read property 'checked' of undefined

java - 如何模拟 "server - android device"通信

Android 可绘制工具提示箭头框

javascript - 通过具有子对象的对象进行映射 - Javascript

javascript - Angular Bootstrap 下拉切换不起作用

javascript - 使用简单的 JavaScript 或 jQuery 分别识别每个选择选项并在 DIV 中显示

java - Android:为什么我不能从 View 中覆盖 setFrame?

reactjs - 如何在 react 中重置子组件状态

javascript - 如何正确对齐按钮内的 material-ui 图标?