reactjs - 在 React.JS 中刷新后如何让用户保持登录到 firebase
问题描述
这里有一个类似的问题,建议的答案似乎对我不起作用。
这是我使用 Firebase 移动登录来登录 ReactJS 的方式。我还在登录时设置身份验证状态持久性(请参见下面的代码)。
但是,当我在登录后刷新页面时,用户对象消失了,即“用户未登录”消息打印在 componentDidMount 中。
我可能做错了什么?
class SignInScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
isSignedIn: false,
};
}
// Configure FirebaseUI.
uiConfig = {
// Popup signin flow rather than redirect flow.
signInFlow: "popup",
signInOptions: [
{
provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID,
defaultCountry: "US",
},
],
callbacks: {
// Avoid redirects after sign-in.
signInSuccessWithAuthResult: () => false,
},
};
// Listen to the Firebase Auth state and set the local state.
componentDidMount() {
this.unregisterAuthObserver = firebase.auth().onAuthStateChanged((user) => {
this.setState({ isSignedIn: !!user });
if (user != null) {
this.setAuthPersistence(); // Setting state persistence here
}
});
if(firebase.auth().currentUser){
console.log("User is already signed in")
}else{
console.log("User is not signed in")
}
}
setAuthPersistence = () => {
firebase
.auth()
.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(function() {
console.log("Local persistence set");
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("Local persistence has not been set");
});
};
// Make sure we un-register Firebase observers when the component unmounts.
componentWillUnmount() {
this.unregisterAuthObserver();
}
render() {
//Displaying firebase auth when user is not signed in
if (!this.state.isSignedIn) {
return (
<div>
<StyledFirebaseAuth
uiConfig={this.uiConfig}
firebaseAuth={firebase.auth()}
/>
</div>
);
}
return <Redirect to="/signedInUser" />;
}
}
export default SignInScreen;
解决方案
与您链接的答案相同,您if(firebase.auth().currentUser)
在 Firebase 异步刷新身份验证状态之前运行,因此在用户再次登录之前。
任何需要响应身份验证状态的代码都需要在onAuthStateChanged
回调中。所以:
componentDidMount() {
this.unregisterAuthObserver = firebase.auth().onAuthStateChanged((user) => {
this.setState({ isSignedIn: !!user });
if (user != null) {
this.setAuthPersistence(); // Setting state persistence here
}
if(firebase.auth().currentUser){
console.log("User is already signed in")
}else{
console.log("User is not signed in")
}
});
}
推荐阅读
- reactjs - ant design 清除所有复选框
- java - 并发哈希图删除复杂值
- r - R 旋转包含向量的数据框单元格
- javascript - 如何在Javascript中打印一次日期标签
- android - Intellij 2019 2.3 插件 Andriod 支持中的异常
- python - 日期时间转换 ValueError Pandas
- hyperledger-fabric - 使用 vscode 在 ibm 区块链平台中运行 invoke.js 时出错?
- c - C 究竟在哪些情况下会引发分段错误?
- react-native - 在动态端点上打开套接字
- android - 如何修复某些 android 设备(Twilio 可编程视频)中的低远程音频?