【问题标题】:Navigation - Cannot read property 'navigate' of undefined导航 - 无法读取未定义的属性“导航”
【发布时间】:2019-06-06 09:36:26
【问题描述】:

我在登录功能后尝试在“主页”路线上导航,并尝试在登录中集成导航功能,但出现错误“无法读取未定义错误的属性“导航”。

loginUser = (email, password) => {
    try {
        firebase
            .auth()
            .signInWithEmailAndPassword(email, password)
            .then(function(user) {
                this.props.navigation.navigate("Home");
            });
    } catch (error) {
        console.log(error.toString());
    }
};

我也尝试过使用() => this.props.navigation.navigate("Home");,但没有任何反应。

我的路线工作正常,因为如果我用 onPress 功能创建一个简单的按钮,工作正常。

<Button title="Go to Login" onPress={() => this.props.navigation.navigate("Login")} />

你能给我一些提示吗? react-native 登录成功后如何导航到首页?

提前谢谢你!

【问题讨论】:

标签: reactjs react-native navigation


【解决方案1】:

当您使用 function() {} 语法而不是箭头函数语法时,您正在更改 this 的词法范围(在 this.props 中)承诺链。

如果您将函数更改为箭头函数,您将保留外部范围,并可以访问 this

例如

.then((user) => {
   that.props.navigation.navigate("Home");
});

【讨论】:

  • 谢谢@codi05ro - 不幸的是,我真的需要看到更多你的代码。你能具体是什么未定义吗?如果你在 loginUser 方法的第一行使用 console.log(this.props) - 你能看到那里的导航吗?
【解决方案2】:

尝试console.log(this)。我想因为你在promise中创建了一个新函数,所以this的范围已经改变了。尝试

loginUser = (email, password) => { let that = this; try { firebase .auth() .signInWithEmailAndPassword(email, password) .then(function(user) { that.props.navigation.navigate("Home"); }); } catch (error) { console.log(error.toString()); } };

【讨论】:

  • 感谢您的回答。我已经尝试过,但现在我得到'未定义'
猜你喜欢
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 2020-09-26
  • 2018-10-02
  • 1970-01-01
相关资源
最近更新 更多