ReactJs路由:设置一条非常基本的专用路由

时间:2020-02-18 15:09:47

标签: reactjs react-router react-router-v4 react-router-dom

App.js

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import ParentComponent from "./Components/nestedComponents/ParentComponent";
import NavBar from "./Components/Shared/NavBar";

//Protecting a route
import PrivateRoute from "./common/PrivateRoute";
import ProtectedComponent from "./Components/Protected/ProtectedComponent";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <NavBar />
        <Switch>
          <Route path="/home" name="Home" component={ParentComponent} />
          <PrivateRoute
            exact
            path="/protectedRoute"
            component={ProtectedComponent}
          />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

ProtectedComponent.js

import React from "react";

export default function ProtectedComponent() {
  return (
    <div>
      This is a protected component. It can only be accessed under certain
      conditions.
    </div>
  );
}

PrivateRoute.js

import React from "react";
import { Route, Redirect } from "react-router-dom";
const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props => (false ? <Component {...props} /> : <Redirect to="/" />)}
  />
);

export default PrivateRoute;

目前,取决于此语句中的布尔值:

render={props => (false ? <Component {...props} /> : <Redirect to="/" />)}

如果为假,路由器将重定向到“ /” ,或重定向到 ProtectedComponent ,该组件将传递到< strong> App.js 。

因此,如果我单击右侧的 ProtectedComponent ,它的行为应与我刚才提到的一样。
enter image description here
但是,当我单击时,当布尔值是 false 时,我不会重定向到“ /” ,并且当布尔值是 ProtectedComponent 时,我不会被重定向布尔值是 true 。只是什么都没有被渲染。
enter image description here
这是指向Github project

的链接

0 个答案:

没有答案