簡體   English   中英

如何使用 react-router 使用私有路由?

[英]How to use Private Route using react-router?

我想使用身份驗證建立安全路由。 我已經在 App.jsx 文件中定義了路由。 我正在使用“路由”來定義要呈現的組件。

在 App.jsx 中

<Route 
    path='/dashboard'
    exact={true}
    render={(props) => <Dashboard {...props} user={user} 
    handleChildFunc={this.handleChildFunc}/>}
/>

上面的代碼沒有任何問題。 我想讓它像下面一樣安全。

<PrivateRoute 
    path='/dashboard'
    exact={true}
    render={(props) => <Dashboard {...props} user={user} 
    handleChildFunc={this.handleChildFunc}/>}
/>

在 PrivateRoute.jsx 中

const PrivateRoute = ( props ) => {
  const user = "token from cookie"; // i will fetch token stored in cookie
  if(user !== null) {
    return <Route   />;
  }
  else {
    return <Redirect to="login" />
  }
}

如果令牌存在,則呈現組件。 否則,重定向到 /login。

你可以擁有你的PrivateRoute

<PrivateRoute 
    path='/dashboard'
    exact={true}
    component={Dashboard}
    handleChildFunc={this.handleChildFunc}
/>
const PrivateRoute = ({ component: Component, handleChildFunc, ...rest }) => {
    const user = "token from cookie";
    return <Route {...rest} render={(props) => (
        user !== null
            ? <Component {...props} user={user} handleChildFunc={handleChildFunc}/>
            : <Redirect to='/login' />
        )} 
    />
}

接受的答案很好,但是當我們需要我們的組件來反映 URL 中的更改時,它並不能解決問題。

假設您的組件具有以下代碼:

export const Customer = (props) => {

   const history = useHistory();
   ...

}

然后您更改您的網址:

const handleGoToPrev = () => {
    history.push(`/app/customer/${prevId}`);
}

該組件不會重新加載!


改進的解決方案:

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import store from '../store/store';

export const PrivateRoute = ({ component: Component, ...rest }) => {

  let isLoggedIn = !!store.getState().data.user;

  return (
    <Route {...rest} render={props => isLoggedIn
      ? (
        <Component key={props.match.params.id || 'empty'} {...props} />
      ) : (
        <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
      )
    } />
  )
}

用法:

<PrivateRoute exact path="/app/customer/:id" component={Customer} />

簡單地 !

  export default function RouteComponent() {
  const user = useContext(UserContext);

  return (
    <Router>
      {user.islogin ? (
        <div className="main_container">
          <Nav />
          <Switch>
            <Route exact path="/">
              <Home />
            </Route>
            <Route path="/NewActiv">
              <NewActiv />
            </Route>
          </Switch>
        </div>
      ) : (
        <Switch>
          <Route exact path="/">
            <Login />
          </Route>
        </Switch>
      )}
    </Router>
  );
}
export default function RouteComponent() {
  const user = useContext(UserContext);

  return (
    <Router>
      {user.islogin ? (
        <div className="main_container">
          <Nav />
          <Switch>
            <Route exact path="/">
              <Home />
            </Route>
            <Route path="/NewActiv">
              <NewActiv />
            </Route>
          </Switch>
        </div>
      ) : (
        <Switch>
          <Route exact path="/">
            <Login />
          </Route>
        </Switch>
      )}
    </Router>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM