reactjs - 当用户未登录应用程序时如何重定向到登录页面
问题描述
我在我的 React 项目中使用 Firebase。当用户尚未登录时,应用程序不会重定向到登录页面的问题。
在我的Home.js
我有这个页面只允许已经登录应用程序的用户。
class Home extends React.Component {
constructor(props) {
super(props);
}
logout = () => {
firebase.auth().signOut();
this.props.history.push("/login");
};
render() {
if (firebase.auth().currentUser === null) {
return <Redirect to="/login" />;
}
return (
<div>
<div>
<Button variant="contained" color="primary" onClick={this.logout}>
Google Logoout
</Button>
</div>
</div>
);
}
}
export default withRouter(Home);
实际上,我用于分类用户是否登录firebase.auth().currentUser
。
解决方案
一个简单的。这可以通过使用onAuthStateChanged
from firebase 来完成,如下所示:
firebase.auth().onAuthStateChanged(user => {
user ? history.push("/dashboard") : history.push("/login");
renderApp();
});
如果有用户,将他重定向到我的案例仪表板,如果没有,将他重定向到登录。
推荐阅读
- java - 尝试创建循环时不断收到 java.util.NoSuchElementException 错误
- c - 交叉编译的根文件系统中未声明的变量
- c# - 在应用程序的另一部分检索 IApplicationBuilder 和 IWebHostEnvironment
- javascript - 如何修复设计中给出的滑块的导航和点
- python - 为什么 spacy ner 的结果是高度不可预测的?
- html - 步骤进度条在移动设备中是水平的
- big-o - python itertools.permutation 中置换算法的大 O 表示法
- r - 解压文件时出错:从 zip 文件中提取时出现错误 1
- c - 如何在 xlib 的窗口中显示 xmp 图像文件?(我正在用 C 编码)
- java - 如何使用 stomp over spring boot websockets 从客户端接收文件作为私人消息?