javascript - 反应路由器身份验证
问题描述
我是 React.js 的初学者,我正在使用 Firebase 和 React Router。我已经设置了一个单独的Auth.js
文件(导出一个布尔值),我在其中存储用户的身份验证状态并且它按预期工作,但问题是当我登录/注册或注销时,内容不会更改/重新呈现。在其他文件中记录导出的布尔值我发现它由于某种原因没有改变。
认证
import fire from './Fire';
var isAuth = false;
fire.auth().onAuthStateChanged(
function (user) {
if (user) {
isAuth = true;
console.log('Authed');
} else {
isAuth = false
console.log('Not Auth');
}
}
);
export default isAuth;
然后是Router.js
import React, { Component } from 'react';
import { Route, Switch, Redirect } from "react-router-dom";
import Login from './components/common/Navbar/Login/Login';
import Register from './components/common/Navbar/Register/Register';
import Home from './components/common/Home/Home';
import isAuth from './config/isAuth';
import All from './components/All/All';
import PrivateRoute from './config/PrivateRoute';
class Router extends Component {
constructor(props) {
super(props);
this.state = ({
isAuth: isAuth
});
}
componentWillMount() {
this.setState = ({
isAuth: isAuth
});
}
render() {
console.log('Router.js => ' + this.state.isAuth)
return (
<div>
<PrivateRoute exact path='/' component={Home} />
<PrivateRoute exact path='/register' component={
this.state.isAuth ? Home : Register} />
<PrivateRoute exact path='/all' component={All} />
<Route exact path='/login' component={ this.state.isAuth ? Home : Login} />
</div>
);
}
}
export default Router;
最后是我从互联网上某人的代码中获取的PrivateRoute组件。
import React from 'react';
import { Redirect, Route } from "react-router-dom";
const PrivateRoute = ({ component: Component, ...rest }, isLogged) => (
<Route {...rest} render={(props) => (
isLogged
? (<Component {...props} /> )
: (<Redirect to={{ pathname: '/login' }} />)
)} />
)
export default PrivateRoute;
解决方案
我认为你这样做的方式不会改变 isAuth 状态。你可以试试这个解决方案吗?我希望它会工作
class Router extends Component {
constructor(props) {
super(props);
this.state = ({
isAuth: false
});
}
componentDidMount() {
fire.auth().onAuthStateChanged((user) => {
if (user) {
console.log(user);
this.setState({ isAuth: true });
} else {
this.setState({ isAuth: false });
}
});
}
render() {
console.log('Router.js => ' + this.state.isAuth)
return (
<div>
<PrivateRoute exact path='/' component={Home}/>
<PrivateRoute exact path='/register' component={
this.state.isAuth ? Home : Register} />
<PrivateRoute exact path='/all' component={All}/>
<Route exact path='/login' component={ this.state.isAuth ? Home : Login} />
</div>
);
}
}
推荐阅读
- html - 如何强制浏览器清除缓存以显示我网站上的更改?
- r - zip_internal 错误(zipfile,文件,递归,compression_level,append = FALSE,:某些文件不存在
- python - 如何搜索列表中的数字是否存在于另一个列表中?
- c++ - 端口转发错误:端口转发未转发到服务器
- azure - Azure DataFactory 复制数据 - 如何知道它已完成复制数据?
- javascript - 正确使用 HTML 下载属性
- npm - Travis CI 中的“gatsby build”失败 - 错误 #98123 WEBPACK
- uwp - 从 UWP 应用访问 Microsoft Dynamics
- r - 存在联系时的优化:与其他约束一起
- database - 将多个数据库/目录同步到一个目录的最佳企业工具