[web前端] react router4.0 登录后返回之前浏览页面,回到来源页

本文链接:https://blog.csdn.net/zeroyulong/article/details/81911704

困扰了好久的问题,最终还是在官方文档上找到了答案(看英文文档真心难受啊~~)

官方文档地址:https://reacttraining.com/react-router/web/example/auth-workflow

1.来源页中跳转登录按钮:

将本页pathname存放到路由state中,

<Link to={{
    pathname:"/login",
    state:{from:this.props.location.pathname}
}} className="name-load">去登录</Link>

  

2.跳转到登录页面后,获取来源,登录完成后页面重定向至来源页面(判断是否有来源页面,若用户直接进入的是登录页面,则无法获取state,此时应提供一个默认首页供用户跳转)

//来源记录
let from;
if(this.props.location.state != null){
    from = this.props.location.state.from
}
const urlTo = from ||'/App';

return (
    <div>
        {this.props.isAuth?<Redirect to={urlTo} />:null}
        <p>你没有权限,需要登录才能看</p>
        <button onClick={this.props.login}>点我登录</button>
    </div>
)