Rba*_*bar 6 javascript firebase reactjs react-router firebase-authentication
我正在为使用 firebase 的用户创建一个帐户。创建帐户后,我重定向到主页,它检查我是否登录。奇怪的是,我没有登录。
在创建帐户页面上:
createAccount() {
firebaseAuth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((user) => {
// write some data to database
firebase.database().ref().child('users').child(user.uid).child('someKey').set(this.state.email).then(function() {
// send email verification
user.sendEmailVerification().then(function() {
console.log("sent email verification");
// Go to home page
this.props.history.push('/home');
}.bind(this)).catch(function(error) {
console.log("Error: account created but no verification email sent.");
}.bind(this));
}.bind(this)).catch((error) => {
console.log('Error: while writing to database');
});
// catch any error while creating user
}).catch((error) => {
console.log('Error: while creating account');
});
}
Run Code Online (Sandbox Code Playgroud)
在主页上:
componentDidMount() {
firebase.auth().onAuthStateChanged(function (user) {
if (!user) {
console.log("no user logged in");
this.props.history.replace('/login'); // ISSUE: Always redirected to login, even after signup and login
return
} else {
console.log("Woo! User is logged in!");
}
}.bind(this))
}
Run Code Online (Sandbox Code Playgroud)
替代尝试:
this.createAccount为() => this.createAccountforonClick处理程序(结果相同)firebase.auth()而不是firebaseAuth()(相同的结果)有谁明白为什么我没有登录?
**编辑: **
以下是我如何初始化我的应用程序:
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "XXXXXXXXX",
authDomain: "myproject.firebaseapp.com",
databaseURL: "https://myproject.firebaseio.com",
projectId: "XXXXXXXXX",
storageBucket: "XXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXX"
};
firebase.initializeApp(config);
</script>
Run Code Online (Sandbox Code Playgroud)
可能值得注意的是:如果我使用不是刚刚创建的帐户登录(或者如果我等待一段时间然后登录到我创建的帐户),则保留授权似乎没有问题重定向。似乎只有当我创建一个新用户然后重定向它才会丢失登录用户。
我有相同的设置并且工作正常。
我的路由器顶部有我的身份验证状态更改侦听器......
state = { user: null };
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setState({ user });
} else {
this.props.history.push('/login');
}
});
}
Run Code Online (Sandbox Code Playgroud)
在 Login.js 中,我有一个表单连接到类似于您的登录功能......
login() {
firebase
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.then(res => {
this.props.history.push('/');
})
.catch(err => console.error(error));
}
Run Code Online (Sandbox Code Playgroud)
我唯一能想到的就是你给了history.replace,尝试更改为history.push。
| 归档时间: |
|
| 查看次数: |
2801 次 |
| 最近记录: |