如何重定向到登录页面?

时间:2021-03-01 12:48:55

标签: reactjs react-router-dom

我在我的项目中使用 react-router-dom。我有一个名为 auth 的值,我从 localStorage 获取它 我想在 auth 没有值时转到登录页面..如何重定向?

  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>
        );

3 个答案:

答案 0 :(得分:1)

您需要一个路由器防护,使用 this 包,您可以简单地创建路由器防护。

例如:

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { GuardProvider, GuardedRoute } from 'react-router-guards';
import { About, Home, Loading, Login, NotFound } from 'pages';
import { getIsLoggedIn } from 'utils';
 
const requireLogin = (to, from, next) => {
  if (to.meta.auth) {
    if (getIsLoggedIn()) {
      next();
    }
    next.redirect('/login');
  } else {
    next();
  }
};
 
const App = () => (
  <BrowserRouter>
    <GuardProvider guards={[requireLogin]} loading={Loading} error={NotFound}>
      <Switch>
        <GuardedRoute path="/login" exact component={Login} />
        <GuardedRoute path="/" exact component={Home} meta={{ auth: true }} />
        <GuardedRoute path="/about" exact component={About} meta={{ auth: true }} />
        <GuardedRoute path="*" component={NotFound} />
      </Switch>
    </GuardProvider>
  </BrowserRouter>
);

答案 1 :(得分:1)

不知道为什么要分开 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>
        );
    }

试试代码,让我知道它对你有什么作用。

答案 2 :(得分:1)

  const signInWithToken = async (token) => {
    try {
      await firebase.auth().signInWithCustomToken(token);
    } catch (error) {
      console.log('error.message', error.message); //eslint-disable-line
    }
  };

  React.useEffect(() => {
    const cookieArr = document.cookie
      .split(';')
      .map((ck) => ({ [ck.split('=')[0].trim()]: ck.split('=')[1] }));
    const tokenCookie = cookieArr.find((el) => Object.keys(el).includes('token'));

    if (!tokenCookie) {
      return;
    }
    signInWithToken(tokenCookie.token);
    getBrandData();
  }, []);