我是一名学习React的学生。我正在尝试创建一个Web应用程序,用户在该Web应用程序中必须先使用Google登录才能查看任何内容。我从github-notetaker
示例中的代码开始,并已编辑Main.js
。到目前为止,我正在将整个逻辑写入init()
方法内部,并在loggedIn
中设置email
和this.state
值。
import React from 'react';
import { RouteHandler } from 'react-router';
import Rebase from 're-base';
class Main extends React.Component{
constructor(props){
super(props);
this.state = {
loggedIn: props.loggedIn,
email: props.email
};
}
authDataCallback(authData) {
if (authData) {
console.log('User is already logged in.');
console.log(authData["google"]["email"]); // works as expected
this.setState({
loggedIn: true,
email: authData["google"]["email"]
});
console.log(this.state.email); // does not work as expected
} else {
this.setState({
loggedIn: false
});
console.log('Attempting to authenticate user account');
this.ref.authWithOAuthPopup('google', function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully');
}
}, {
scope: "email"
});
}
}
init(){
console.log('Init called');
this.ref = new Firebase('https://myapp.firebaseio.com/');
this.ref.onAuth(this.authDataCallback.bind(this));
}
componentWillMount(){
this.router = this.context.router;
}
componentDidMount(){
this.init();
}
componentWillReceiveProps(){
this.init();
}
render(){
if (!this.state.loggedIn) {
return (
<div className="main-container">
<div className="container">
<h3>You are not authenticated. <a href="">Login</a></h3>
</div>
</div>
)
} else {
return (
<div className="main-container">
<div className="container">
<RouteHandler {...this.props}/>
</div>
</div>
)
}
}
};
Main.propTypes = {
loggedIn: React.PropTypes.bool,
email: React.PropTypes.string
};
Main.defaultProps = {
loggedIn: false,
email: ''
}
Main.contextTypes = {
router: React.PropTypes.func.isRequired
};
export default Main;
我遇到一个奇怪的错误,并相信我这样做的方式是错误的。用户成功验证后,将保存所有信息并写入用户的
email
。控制台日志如下所示:User is already logged in.address@email.com // corresponds to authData["google"]["email"]address@email.com // corresponds to this.state.email = CORRECT!!
但是,当我刷新页面时,新的打印看起来像这样,看来电子邮件和对象仍然对我可用,但没有保存在
this.state
中。User is already logged in.address@email.com // corresponds to authData["google"]["email"]null
我目前正在学习React,所以这可能是一个非常简单的错误。非常感谢您的宝贵时间和事先的帮助。如果您能为我指明正确的方向,或者让我知道一种更好的方法,我将不胜感激。谢谢!
最佳答案
您编写的代码错误。var currentAuthData = this.ref.getAuth();
向fireBase发送请求以获取身份验证,但是在fireBase可以检索正确的信息之前运行下一行代码if (currentAuthData) {
。
您必须改为使用回调函数。
ref.onAuth(authDataCallback);
function authDataCallback(authData) {
if (authData) {
console.log('User is already logged in.');
}
}