2016-07-06 64 views
3

基本想法是在React中進行Firebase登錄。Firebase通過React組件登錄

組件呈現自己,但他們不一起工作。主要的問題是在調用onAuthStateChanged()方法之後,render函數不會採用«new»狀態。我究竟做錯了什麼?

非常感謝你們!

var Login = React.createClass ({ 

    getInitialState: function(){ 
     return { loggedIn: 'false' }; 
    }, 

    handleLogIn: function(event){ 

     var email = document.getElementById('email').value; 
     var password = document.getElementById('password').value; 

     firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) { 
     // ERROR HANDLING 
     var errorCode = error.code; 
     var errorMessage = error.message; 

     // [... error handling ...] 

     }); 

     this.setState({ loggedIn: 'true' }); 

    }, 

    authenticateUser: function(x){ 

    // INITIALIZATION 
    var config = { 
     [ ... config stuff ... ] 
    }; 
    firebase.initializeApp(config); 

    //CHECKING IF SIGNED IN 
    firebase.auth().onAuthStateChanged(function(user) { 
     if (user) { 
     // USER IS SIGNED IN 
     console.log('authenticateUser(): true'); 
     this.setState({ loggedIn: 'true' }); 
     } 
     else { 
     // USER IS SIGNED OUT 
     console.log('authenticateUser(): false'); 
     this.setState({ loggedIn: 'false' }); 
     } 
    }); 
    }, 

    whichWindowToShow: function() { 
    if (this.state.loggedIn === 'unknown'){ 
     return (
     <div> 
     <Loading type='bubbles' color='#e3e3e3' /> 
     </div> 
    ); 
    } 
    else if (this.state.loggedIn === 'true'){ 
     return (
     <div> 
     <Backend /> 
     </div> 
    ); 
    } 
    else { 
     return (
     <div className="login_wrapper"> 
     <div className="login_box"> 
     <h1>Member Login</h1> 
      <div className="login_fields"> 
      <input type="text" id="email" name="email" placeholder="mail"/> 
      <input type="password" id="password" name="password" placeholder="password"/> 
      <button id="signin" name="signin" onClick={this.handleLogIn}>Login</button> 
      </div> 
     </div> 
     </div> 
    ); 
    } 
    }, 

    render: function() { 
    this.authenticateUser(); 
    return (
     <div> 
     { this.whichWindowToShow() } 
     </div> 
    ); 
    } 
}); // END LOGIN 

回答

5

對於所有有同樣的問題/挑戰,

這是最終的最終解決方案(.bind(本)做的工作)。

也應所有其它火力地堡聽衆(。對(例如, 「值」))

firebase.auth().onAuthStateChanged(function(user) { 
    if (user) { 
    this.setState({ loggedIn: "true" }); 
    } 
    else { 
    this.setState({ loggedIn: "false" }); 
    } 
}.bind(this)); 
+0

或可以分配給一個'''this.removeListener = firebase.auth()施加.. ..'''並在componentWillUnmount中執行它...你的方法雖然更優雅。 – archae0pteryx