如何通过react-router使用Private Route?

时间:2019-08-26 15:28:50

标签: reactjs 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。

3 个答案:

答案 0 :(得分:1)

您可以像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' />
        )} 
    />
}

答案 1 :(得分:0)

可接受的答案很好,但是当我们需要我们的组件来反映URL的更改时并不能解决问题。

说,您的组件具有以下代码:

abs(d)

您更改了网址:

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 } }} />
      )
    } />
  )
}

答案 2 :(得分:0)

简单!

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