我正在为我的前端使用Reactjs的Web应用程序。我阻止用户访问某些页面,例如他们已登录。我的问题是如何让用户访问他们预期的网址,而不是将他们重定向到我目前所做的主页。登录后将用户重定向到指定的网址Reactjs
我的路线是
<Switch>
<Route path="/desired-page" component={requireAuth(DesiredPage)} />
<Route path="/new-page" component={requireAuth(NewPage)} />
</Switch>
我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
}
}
return connect(mapStateToProps, { addFlashMessage })(Authenticate);
}
你的意思是他们登录后?你没有显示那部分代码。在内部'if(!this.props.isAuthenticated){'将URL保存为某种全局状态(例如,您的redux商店)。然后在成功登录后重定向到该页面。 –
是的,他们登录后。我想到了这一点,但如何实施已成为一项挑战 – Dayvino
将网址保存到全球商店并检索它一直是我面临的主要挑战。你能给一个指针吗? – Dayvino