React Native,Navigation:" Undefined不是一个对象"

时间:2017-09-17 15:14:55

标签: react-native navigation

我尝试在登录成功时重定向我的用户,但我收到了此错误:"未定义不是对象(评估' _this2.props.navigation')&#34 ;

这是我在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);
    });
}

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

1 个答案:

答案 0 :(得分: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))