【问题标题】:React Native, Navigation: "Undefined is not an object"React Native,导航:“未定义不是对象”
【发布时间】:2017-09-17 23:22:32
【问题描述】:

当我的用户登录成功时,我正尝试重定向,但我收到此错误:“未定义不是对象(正在评估'_this2.props.navigation')”

这是我在 App.js 中的代码:

const Homepage = StackNavigator({
 Home: {screen: Home},
 Store: {screen: Store},
 Admin: {screen: Admin},
});

这是我在 Store.js 中的代码,我尝试在用户登录后重定向用户:

<Button style={{color:'gray', borderColor: 'gray'}} onPress={() => 
this.login()} title="Me connecter" />

login(){
    firebase.auth().signInWithEmailAndPassword(this.state.emailLogin, 
    this.state.passwordLogin).then(function(user) {
        // Send the user to the next step
        setTimeout(() => {
            const { navigate } = this.props.navigation; 
            navigate('Admin');
        }, 1500);
    }).catch(function(error) {
        console.log('error');
        var errorCode = error.code;
        var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password') {
            alert('Wrong password.');
        } else {
            alert(errorMessage);         
        }
        console.log(error);
    });
}

提前感谢您的宝贵时间和宝贵的答案。

【问题讨论】:

    标签: react-native navigation


    【解决方案1】:

    为了能够使用this,你需要绑定函数,

    更改此代码,

    firebase.auth().signInWithEmailAndPassword(this.state.emailLogin, 
        this.state.passwordLogin).then(function(user) { /* rest of your code */ })
    

    到这里,

    firebase.auth().signInWithEmailAndPassword(this.state.emailLogin, 
        this.state.passwordLogin).then((user) => { /* rest of your code */ })
    

    或者这个,

    firebase.auth().signInWithEmailAndPassword(this.state.emailLogin, 
        this.state.passwordLogin).then(function(user) { /* rest of your code */ }.bind(this))
    

    【讨论】:

    • 这两个函数都必须绑定 this 或箭头函数。我的意思是 setTimeout 的函数也应该绑定。
    • @Kyon setTimeout 如果我没看错的话已经是一个箭头函数
    • 好的,我删除了 timeoute,因为它没有用。我使用了第二个命题,它起作用了。所以谢谢你们两个:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多