我正在开发一个使用 Reactjs 作为前端的 Web 应用程序。我阻止用户访问某些页面,除非他们已登录。我的问题是如何允许用户访问他们想要的 url,而不是将他们重定向回我当前所做的主页。
我的路线是
<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);
}
最佳答案
因此,ReactTraining Docs 为您提供了一个 location
属性,它代表应用程序现在的位置、您希望它去的位置,甚至是它曾经在的位置。
导航到登录
路线时,您可以提及从哪个路线导航到登录的状态。你可以这样做
- 重定向至
- 历史记录.push
- 历史.替换
要动态路由,您可以使用 history.push
传递它,例如
const location = {
pathname: '/login'
state: { from: 'Main' }
}
history.push(location)
就你的情况而言,它将是
import {withRouter} from 'react-router';
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'
});
const location = {
pathname: '/login'
state: { from: {pathname: '/Main'} }
}
this.props.history.push(location);
}
}
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 })(withRouter(Authenticate));
}
现在,在登录后重定向回来时,您可以使用以下方式访问此参数
var {from} = this.props.location.state || {from: {pathname: '/'}}
this.props.history.push(from)
NOTE: When you want to make use of
history
object from prop make sure to wrap your component withwithRouter
HOC.
我希望这有帮助:)
关于routes - 登录后将用户重定向到预期的 url Reactjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44649665/