首页 文章

react-route>登录后重定向到请求的内容

提问于
浏览
0

我使用react和react-route进行身份验证 . 我的目标是:

  • 菜单栏上的登录链接,用户可以通过此链接登录

  • 如果用户已登录,则我需要在页面顶部显示不同的菜单结构

  • 如果用户刷新浏览器的内容,则需要呈现不同的菜单,这取决于用户的状态(登录或匿名用户)

  • 如果匿名用户点击非公开的链接,则需要自动显示登录表单

  • 成功登录后,用户需要重定向到请求的内容

我的解决方案工作正常(如果有人对我感兴趣,我会在这里发布我的代码) .

我有一个与我上一个目标有关的问题,(5) . 我不知道跨层发送原始请求的路径信息的最佳做法是什么 . 首先请求的路径出现在App.js(Route)中 . 然后需要传递给onEnter方法 . 如果它是一个匿名用户,则需要将所请求的路径传递给显示的Login组件,最后在成功登录后,需要对原始请求的路由进行重定向 .

我的解决方案使用url参数将请求的原始路由信息传递给登录组件 .

这是我的代码:

App.js

function requireAuth(nextState, replace) {
    if (!auth.loggedIn())
        replace({
            pathname: '/login?route=' + nextState.location.pathname,
            state: { nextPathname: nextState.location.pathname }
        })
}

ReactDom.render(
    <Router history={hashHistory} onUpdate={() => window.scrollTo(0, 0)}>
        <Route path="/" component={MainLayout}>
            <IndexRoute component={Home} />

            <Route path="login" component={Login} />
            <Route path="login?route=:route" component={Login} />

            <Route path="logout" component={Logout} />
            <Route path="about" component={About} />
            <Route path="profile" component={Profile} onEnter={requireAuth} />
        </Route>
    </Router>,
    document.getElementById('root')
);

Login.js

import React from 'react';

import { withRouter } from 'react-router';
import auth from '../auth/Auth';
import Button from "react-bootstrap/lib/Button";

export default class Login extends React.Component {

    doRedirect() {
        if (this.props.location.query.route)
            this.props.router.push(this.props.location.query.route);
        else
            this.props.router.push('/');
    }

    render() {
        return (
            <div style={style.text}>
                <h3>LOGIN FORM</h3>
                <Button bsStyle="primary" onClick={() => auth.login("username", "password", this.doRedirect.bind(this))}>
                    Login
                </Button>
            </div>
        );
    }
}

// wrap with the withRouter HoC to inject router to the props, instead of using context
export default withRouter(Login);

是否有更好的OR更多反应一致的解决方案将请求的uri传递给Login组件?

谢谢 .

2 回答

  • 0

    我不知道反应一致的解决方案 . 但是auth重定向以不同的方式处理它 . 在配置文件页面(经过身份验证的用户视图内容)验证了身份验证而不是路由中的OnEnter . 透视图为匿名用户提供了在视图中呈现不同信息的选项 .

    export default class ProfilePage extends React.Component {	
    	
       constructor(props) {
    		super(props)
    		this.renderProfile=this.renderProfile.bind(this)
    		this.renderAskToLogin=this.renderAskToLogin.bind(this)
    		this.handleOnLoginBtnTap = this.handleOnLoginBtnTap.bind(this);
    		this.getProfiles = this.getProfiles.bind(this);
    		this.reloadProfiles =this.reloadProfiles.bind(this);
    		this.state = {
    		  Profiles: ProfileStore.getAll()
    		};
      }	
      
        
      handleOnLoginBtnTap(){
    		 this.context.router.replace({
    			  pathname: '/login',
    			  state: { nextPathname: '/Profile' }
    			})
      }
    	
      render() {
    	const { loginId, authenticated} = Auth.loggedIn()   
    	return ( 
    			<div>
    				{authenticated? this.renderProfile() : this.renderAskToLogin()}
    			</div>
    		)
      }
      
      
     renderProfile() {
    		const { Profiles } = this.state;
    
    		const ProfileComponents = Profiles.map((Profile) => {
    			return <Profile  key={Profile.name} {...Profile}/>;
    		});
    	  
    		return (
    				<div>
    				<h4> Welcome to <b>ProfileGroup</b> </h4>				
    					<button onClick={this.reloadProfiles}>Refresh!</button>
    					<h1> Profile List</h1>
    					<ul>{ProfileComponents}</ul>
    				</div>
    		)
      }
      
      renderAskToLogin() {
        return (
    			<div>
    			<h4 className='red-txt'>Welcome to <b>Profile Group</b>.You are not yet authendicated.	</h4>
    			<h4> If you want to login, please tap Login button</h4>
    			<button ref='loginBtn' className="btn btn-primary" onClick={this.handleOnLoginBtnTap}> Log In</button>
    			</div>
          )
      }
      
    }
    
    ProfilePage.contextTypes = {
    		router: React.PropTypes.object.isRequired
    	}
    
  • 0

    根据我的代码,在用户点击登录时触发的ProfilePage handleOnLoginButton() . 在该处理程序中,将nextpath设置为当前页面并重定向到loginpage . 在loginpage中,handleOnLoginBtnTap()事件句柄成功登录后重定向到状态中存在的nextpath .

    //Login Page
     handleOnLoginBtnTap(){
    				console.log("Login validation in progress ..")
    				Auth.login(this.state.loginId, this.state.loginPwd, (loggedIn) => {
    					if (!loggedIn)
    					{
    						alert("Login Validation failed. login Id and password should be same");
    						return;
    					}
    
    					const { location } = this.props
    
    					if (location.state && location.state.nextPathname) {
    							this.context.router.replace(location.state.nextPathname)
    					} else {
    						this.context.router.replace('/')
    					}
    				})
      }
    

相关问题