首页 > 解决方案 > 如何重定向到登录页面?

问题描述

react-router-dom在我的项目中使用。我有一个名为authAnd I get it from localStorage And I want to go to the login page when authhas no value ..如何重定向?

  return (
            this.state.auth ?
           
                <div className="wrapper" >
                  
                    <div id='content' className={this.state.isSidebarActive ? "content" : "content-active"}>
            
                        <Switch>
                            <Route exact path='/main' >
                                <Redirect to='/main/customers/real' />
                            </Route>
                            <Route path="/main/access/deny"><NoAccess  isSidebarActive={this.state.isSidebarActive} /></Route>
                            ....
                        </Switch>
                    </div>
                </div>
                : 
 <Switch>
                        <Route exact path='/' >
                            <Redirect to='/Login' />
                        </Route>
                       
                    </Switch>
        );

标签: reactjsreact-router-dom

解决方案


不知道为什么要分开 switch router 语句,但最好将它们放在一起。

<Switch>
    <Route exact path='/main' > <Redirect to='/main/customers/real' /> </Route>

    <Route path="/main/access/deny"><NoAccess  isSidebarActive={this.state.isSidebarActive} /></Route>

    <Route exact path='/' > <Redirect to='/Login' /> </Route>

</Switch>

我也不知道你为什么要重定向这么多次。在进入永恒循环之前,您可能需要注意这一点。

更新

我喜欢对正在做的事情非常明确,所以我将三元语句切换到下面。

    if(this.state.auth != null)
    {
        return(
            <div className="wrapper">
                <div id='content' className={this.state.isSidebarActive ? "content" : "content-active"}>
                    <Switch>
                        <Route exact path='/main' >
                            <Redirect to='/main/customers/real' />
                        </Route>
                        <Route path="/main/access/deny"><NoAccess  isSidebarActive={this.state.isSidebarActive} /></Route>
                        ....
                    </Switch>
                </div>
            </div>
        );
    }
    else
    {
        return(
            <Switch>
                <Redirect to='/Login' />
            </Switch>
        );
    }

试试代码,让我知道它是如何为你工作的。


推荐阅读