【问题标题】:How to use Private Route using react-router?如何使用 react-router 使用 Private Route?
【发布时间】:2019-12-30 19:38:58
【问题描述】:

我想使用身份验证创建安全路由。我已经在 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。

【问题讨论】:

  • 我已经为私人路线创建了gist,如果你想查看的话。
  • 您正在使用 。但在我的例子中,路由是这样定义的: }/>。我该如何修改代码?我没有使用组件 = {组件}。因为我想将道具传递给组件。

标签: reactjs react-router


【解决方案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' />
        )} 
    />
}

【讨论】:

  • 谢谢。有效。我还找到了另一种方法。 const PrivateRoute = ( {path, exact, render} ) => { const user = null; if(user !== null) { return } else { return } }
【解决方案2】:

接受的答案很好,但它不能解决问题当我们需要我们的组件来反映 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} />

【讨论】:

  • 动态 url 部分和一般情况下的绝佳解决方案。
  • 您应该链接到特定的答案,而不是说“接受的答案”。这可能会改变。
【解决方案3】:

简单!

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

【讨论】:

    猜你喜欢
    • 2020-02-11
    • 1970-01-01
    • 2018-12-26
    • 2017-05-16
    • 2022-09-23
    • 2019-04-01
    • 1970-01-01
    • 2020-06-09
    • 2020-12-07
    相关资源
    最近更新 更多