简体   繁体   English

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

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

I want to make secure routes using authentication.我想使用身份验证建立安全路由。 I have defined the routes in App.jsx file.我已经在 App.jsx 文件中定义了路由。 I am using "Route" to define which component to render.我正在使用“路由”来定义要呈现的组件。

In App.jsx在 App.jsx 中

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

The above code works without any issue.上面的代码没有任何问题。 I want to make that secured like below.我想让它像下面一样安全。

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

In PrivateRoute.jsx在 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" />
  }
}

If the token is present, render a component.如果令牌存在,则呈现组件。 Otherwise, redirect to /login.否则,重定向到 /login。

You can have your PrivateRoute like,你可以拥有你的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' />
        )} 
    />
}

The accepted answer is good, but it does NOT solve the problem when we need our component to reflect changes in URL .接受的答案很好,但是当我们需要我们的组件来反映 URL 中的更改时,它并不能解决问题。

Say, your component has the following code:假设您的组件具有以下代码:

export const Customer = (props) => {

   const history = useHistory();
   ...

}

And you change your URL:然后您更改您的网址:

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

The component will not reload!该组件不会重新加载!


An improved solution:改进的解决方案:

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

Usage:用法:

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

Simply !简单地 !

  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