小编Day*_*ino的帖子

登录 Reactjs 后将用户重定向到预期的 url

我正在开发一个使用 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)

routes reactjs react-jsx react-router

6
推荐指数
1
解决办法
2万
查看次数

标签 统计

react-jsx ×1

react-router ×1

reactjs ×1

routes ×1