我在阻止未经授权的用户访问仅授权的路由/组件时遇到问题 - 例如登录用户仪表板
我有以下代码:
import React from 'react'
//other imports
import {withRouter} from 'react-router'
class User extends React.Component {
constructor(props) {
super(props)
console.log('props', props)
let user = JSON.parse(localStorage.getItem('userDetails'))
if(!user || !user.user || props.match.params.steamId !== user.user.steamId) {
props.history.push('/')
} else {
this.props.updateUserState(user)
this.props.getUser(user.user.steamId)
}
}
//render function
}
//mapStateToProps and mapDispatchToProps
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(User))
路由器:
render() {
return (
<Router>
<div>
<Route exact path="/" component={Main}/>
<Route path="/user/:steamId" component={User}/>
<Route path="/completelogin" component={CompleteLogin}/>
</div>
</Router>
)
}
我尝试记录以检查是否输入了条件,但是我从渲染函数中得到一个错误,说它无法读取 null 的属性。
有没有办法解决我的问题以及更好的方法来满足我的要求?只有授权用户才能严格访问特定组件