reactjs - 使用 React-Router 在 ReactJS 中进行身份验证
问题描述
我有一个简单的route.js
文件
const PrivateRoute = ({ component, ...rest }) => {
const isAuthed = localStorage.getItem('Authorization')
return (
<Route {...rest} exact
render = {(props) => (
isAuthed ? (
<div>
{React.createElement(component, props)}
</div>
) :
(
<Redirect
to={{
pathname: '/login',
state: { from: props.location }
}}
/>
)
)}
/>
)
}
class App extends Component {
componentWillMount() {
if (localStorage.getItem('Authorization')) {
history.push(`${history.location.pathname}`)
}
}
render() {
return (
<Router history={history}>
<div className="App-pageContainer">
<Route exact path="/" render={() => <Redirect to="/login" />} />
<Route path={'/login'} component={Login} />
<PrivateRoute path={'/dashboard'} component={Dashboard} />
</div>
</Router>
)
}
}
export default App
我需要设置条件,如果用户在 localStorage( Authentication
) 中有一个键,那么我想将它重定向到,/dashboard
如果它不包含Authentication
在 localStorage 中,那么我想将它重定向到/login
.
从过去的几天开始,我完全被这个困住了。请帮忙!!!
解决方案
我认为这类问题过于宽泛,无法回答。
但是,您可以按照这篇精彩的帖子来实现该功能。
这是你完成后得到的
import React from 'react'
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from 'react-router-dom'
const fakeAuth = {
isAuthenticated: false,
authenticate(cb) {
this.isAuthenticated = true
setTimeout(cb, 100)
},
signout(cb) {
this.isAuthenticated = false
setTimeout(cb, 100)
}
}
const Public = () => <h3>Public</h3>
const Protected = () => <h3>Protected</h3>
class Login extends React.Component {
render() {
return (
<div>
Login
</div>
)
}
}
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
fakeAuth.isAuthenticated === true
? <Component {...props} />
: <Redirect to='/login' />
)} />
)
export default function AuthExample () {
return (
<Router>
<div>
<ul>
<li><Link to="/public">Public Page</Link></li>
<li><Link to="/protected">Protected Page</Link></li>
</ul>
<Route path="/public" component={Public}/>
<Route path="/login" component={Login}/>
<PrivateRoute path='/protected' component={Protected} />
</div>
</Router>
)
}
推荐阅读
- mysql - 为什么我不能在这里按日期(开始时间)分组?
- tsql - 使用连接 T-SQL 从其他多个表创建表
- node.js - 为什么sequelize默认添加时间戳列(createdAt和updatedAt)?
- pandas - 为什么设置WithCopyWarning?
- c# - DataTrigger 到控件的 Validation.HasError
- bash - shell 脚本将行拆分为多行
- android - Flutter Android 构建未显示 Appium 的资源 ID
- python - 无法使用 Pandas Profiling 的 Profile 报告
- swiftui - 如何让 SwiftUI SidebarMenu 每次都显示相同的 DetailView 而不是创建一个新的(在 macOS 上)
- r - 为 R 中的每个变量绘制单独的箱线图