我正在开发一个使用 Reactjs 作为前端的 Web 应用程序。我阻止用户访问某些页面,除非他们已登录。我的问题是如何允许用户访问他们想要的 url,而不是将他们重定向回我目前所做的主页。
我的路线是
<Switch>
<Route path="/desired-page" component={requireAuth(DesiredPage)} />
<Route path="/new-page" component={requireAuth(NewPage)} />
</Switch>
Run Code Online (Sandbox Code Playgroud)
我的 requireAuth.js 是
export default function(ComposedComponent) {
class Authenticate extends React.Component {
componentDidMount() {
if (!this.props.isAuthenticated) {
this.props.addFlashMessage({
type: 'error',
text: 'You need to login to access this page'
});
this.context.router.history.push('/login');
}
}
render() {
return (
<ComposedComponent {...this.props} />
)
}
}
Authenticate.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
addFlashMessage: PropTypes.func.isRequired
}
Authenticate.contextTypes = {
router:PropTypes.object.isRequired
}
function mapStateToProps(state) {
return {
isAuthenticated: state.auth.isAuthenticated …Run Code Online (Sandbox Code Playgroud)