首页 文章

在浏览器上点击 Refresh 后,进行 React Router v4 登录检查

提问于
浏览
3

我正在使用 react router v4 并尝试实现受保护的 api 视图。 E.g。,如果用户在未登录时转到/add/ url,则会将其重定向到/login/,然后成功登录/add/

我能够使用从这篇文章的想法来实现它。但是,每当加载应用程序的初始 http 请求来自受保护的 URL 时,我都会遇到问题。

E.g。当我进入浏览器'/add/'并点击回车时,我遇到异步问题,我的应用程序没有时间向服务器发出 ajax 请求以检查登录,结果路由器最终路由到/login/因为 ajax auth 请求尚未完成。

有人建议登录工作流程一般应该处理,考虑到用户可以在受保护的 URL(如'/add/')而不是主页'/'上开始会话这一事实吗?

1 回答

  • 3

    找到了一个简单,标准的 React 模式解决方案。除非已完成 ajax 检查中的日志,否则不要渲染<Route>组件。

    因此,当应用程序第一次加载时,将状态checkingLogIn初始化为true并且不会呈现任何<Route>组件,除非它变为false。当 ajax 函数检查登录完成时,调用setStatecheckingLogIn设置为false。这将导致<Route>正确渲染和重定向。

    使用示例代码编辑:

    componentDidMount(){
    // call the ajax function that checks if the user is logged in and update state when it returns; using fetch API here
     fetch(your_url, your_credentials)
       .then(
         that.setState({checkingLogIn: false, isLoggedIn: true})
            )
       .catch(...)
    }
    // render method of the React component
    render(){
        if(this.state.checkingLogIn){
        return (<div>Loading...</div>)
        }
        else {
          return (
           <Route path={some_path} render={props => <SomeComponent {...props} />}></Route>
          )
        }
    
    }
    

相关问题