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

Day*_*ino 6 routes reactjs react-jsx react-router

我正在开发一个使用 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
    }
  }
  return connect(mapStateToProps, { addFlashMessage })(Authenticate);
}
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 5

因此,ReactTraining Docs 为您提供了一个locationprop,它代表应用程序现在的位置、您希望它去往的位置,甚至是它曾经在的位置。

导航到Login路线时,您可以提及有关您从哪条路线导航到登录的状态。你可以这样做

  • 重定向至
  • 历史记录.push
  • 历史.替换

要动态路由,您可以使用history.pushlike传递它

const location = {
  pathname: '/login'
  state: { from: 'Main' }
}

history.push(location)
Run Code Online (Sandbox Code Playgroud)

在你的情况下它将是

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));
}
Run Code Online (Sandbox Code Playgroud)

现在,在登录后重定向回来时,您可以使用以下命令访问此参数

var {from} = this.props.location.state || {from: {pathname: '/'}}
this.props.history.push(from) 
Run Code Online (Sandbox Code Playgroud)

注意:当您想使用historyprop 中的对象时,请确保使用 HOC 包装您的组件withRouter

我希望这有帮助 :)