react router - Redirection after login

后端 未结 7 2494
天命终不由人
天命终不由人 2021-01-30 14:22

Could you please help me in understanding the redirection mechanism I could use with latest version of react router ( v1.1.0 ) . I would like to redirect to a

7条回答
  •  耶瑟儿~
    2021-01-30 14:41

    Wanted to update this thread because I spent a good amount of time digging around on this. In React Router 2.0.x, replaceState is deprecated in favor of replace. See here for details: https://github.com/ReactTraining/react-router/blob/v2.0.0/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors

    The correct way to do this would be something like this:

    function requireAuth(nextState, replace) {
      if (!userExists()) {
        replace({
          pathname: '/signin',
          state: { nextPathname: nextState.location.pathname }
        })
      }
    }
    
    export const renderRoutes = () => (
      
          
          
        
      
    );
    

    Then, in the SignIn component, you can redirect after a successful sign in like this:

    signInFunction({params}, (err, res) => {
      // Now in the sign in callback
      if (err)
        alert("Please try again")
      else {
        const location = this.props.location
        if (location.state && location.state.nextPathname) {
          browserHistory.push(location.state.nextPathname)
        } else {
          browserHistory.push('/')
        }
      }
    })
    

提交回复
热议问题