【问题标题】:React/Firebase - unable to call this.props from within auth functionReact/Firebase - 无法从身份验证函数中调用 this.props
【发布时间】:2016-10-28 14:04:53
【问题描述】:

我有一个登录函数,它通过 Firebase 进行身份验证,然后应该调用从父级传递下来的登录函数作为道具。这里是:

class HeaderParentComponent extends Component { 
    toggleSignupLayoverAction(event){
        this.props.toggleSignupLayover("true")
    }
    signIn(e){

        e.preventDefault();
        var email = $(".login-email").val();
        var password = $(".login-user-password").val();

        firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {  
            var user = firebase.auth().currentUser;
            this.props.logUserIn(user);
        }).catch(function(error) {
        // Handle Errors here.
            var errorCode = error.code;
            var errorMessage = error.message;
  // ...
        });

    }
    render() {
        return (
            <div className="header-inner">
                <span onClick={this.props.toggleMenuOut} className="menuToggle"></span>
                <a className="logo-a-tag" href="#">
                    <img height="25" src="../../images/logo.png" alt="my logo"/>
                </a>
                <form className="header-searchbox">
                    <input placeholder="Search Samples Here..." onChange={this.props.updateSearch} value={this.props.searchInputVal} type="text"></input>
                </form>
                <div className="header-acc"><a className={"login " + this.props.loggedInState} href="#">Login</a><a onClick={this.toggleSignupLayoverAction.bind(this)} className={"create " + this.props.loggedInState} href="#">Create Account</a>
                <div className={"logged-in-header " + this.props.loggedInState}>Hello {this.props.LoggedInUsername}</div>
                </div>
                <div className="login-popup-par">
                    <form>
                        <input placeholder="Email Address" className="login-email" type="text"></input>
                        <input placeholder="Password" className="login-user-password" type="password"></input>
                        <button onClick={this.signIn.bind(this)}>Login</button>
                    </form>
                </div>
            </div>
            )
        }
}

目前从 parent 传下来的 props 有一个基本的 console.log 为“logged in”。它通过 this.props.logUserIn(user); 道具传递。问题是我试图在使用 Firebase 的身份验证成功后调用它,因此为什么我将它放在 .signInWithEmailAndPassword(email, password) 之后的 .then 函数中似乎我无法从 Auth 函数内部调用 this.props.logUserIn 但我不知道为什么。如果我将 props 函数移到 auth 函数之外,它会调用它没有问题。为什么我不能从那里访问道具?

【问题讨论】:

  • 使用箭头函数
  • 小心细化安德鲁

标签: reactjs firebase firebase-authentication


【解决方案1】:

这是因为then(function)by default refers to the window object中匿名函数中的this。您实际上是在尝试执行window.props.logUserIn(user),这显然是不希望的。

为了解决这个问题,您可以使用 ES6 arrow functions 不绑定 this 并引用封闭上下文组件的上下文。使用箭头函数,this 将不是window,而是组件并将正确执行方法:

firebase.auth().signInWithEmailAndPassword(email, password).then((user) => {  
    var user = firebase.auth().currentUser;
    this.props.logUserIn(user);
}).catch((error) => {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
});

在 ES6 之前的一种方法是在常规函数上使用 Function.prototype.bindthis 上下文和其他参数显式绑定到函数。这是一个例子:

firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {  
    var user = firebase.auth().currentUser;
    this.props.logUserIn(user);
}.bind(this));
//...

这是因为this在匿名函数之外是组件,并且上下文被传递给函数。


您需要一个constructor,它在类实例化时被调用,并且需要使用props。见here,使用:

constructor(props) {
    super(props);

    /*this.state = { //for state if needed

    };*/
}  

//...

signIn(e) {
   //...
}

【讨论】:

  • 感谢您的解释,现在为什么没有提到道具是有道理的。我已将此处的另一个函数转换为箭头,但这次它不起作用。相反,我现在收到控制台错误 TypeError:无法读取未定义(…)的属性“道具”。这是这里的代码jsfiddle.net/8qL3fqj3/1 如果你能看一下会很棒
  • 嘿@Andrew 这是所有 JSX 的小提琴。如果你能帮我解决这个问题,我会赞成! jsfiddle.net/8qL3fqj3/2
  • @BenLiger 你需要一个构造方法
  • @BenLiger 是的。它只是类的一种方法。他们构建类并传递道具。查看更新的答案
  • @BenLiger 您在常规函数中有一个箭头函数。检查您的updateProfile 承诺。
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 2020-05-18
  • 2016-04-22
  • 2018-03-10
  • 2017-07-12
相关资源
最近更新 更多