简体   繁体   English

如何将子目录与反应路由器一起使用?

[英]How can I use subdirectories with react router?

I'm new to React and trying to understand routing, in particular how to work with subdirectories in the URL path.我是 React 新手并试图了解路由,特别是如何使用 URL 路径中的子目录。

Here is my App.js file这是我的App.js文件

import React from "react"
import {BrowserRouter as Router, Switch, Route } from "react-router-dom"    
import Home from "./Home"
import About from "./About"
import Contact from "./Contact"
import NavBar from "./NavBar"
import Employees from "./Employees"
import EmployeesCreate from "./EmployeesCreate" 
class App extends React.Component {
    render(){   
        return (
            <Router>
                <div>
                    <NavBar />
                    <Switch>
                        <Route exact path="/">
                            <Home />
                        </Route>
                        <Route path="/about">
                            <About />
                        </Route>
                        <Route path="/contact">
                            <Contact />
                        </Route>
                        <Route path="/employees">
                            <Employees />
                        </Route>
                        <Route path="/employees/Create">
                            <EmployeesCreate />
                        </Route>
                    </Switch>
                </div>
            </Router>
        )
    }
} 
export default App

I'm having trouble with the /employees/create path.我在使用/employees/create路径时遇到问题。 It is loading the Employees component instead of the EmployeesCreate component.它正在加载Employees组件而不是EmployeesCreate组件。

What am I doing wrong?我究竟做错了什么?

The Route component does a substring match and so /employees/create gets matched by the /employees route. Route组件执行 substring 匹配,因此/employees/create/employees路由匹配。 Pass the exact prop to the Route component to make sure it only gets rendered when there's an exact match.exact prop 传递给Route组件,以确保它仅在完全匹配时才被渲染。

From the docs ,文档中,

exact : bool exactbool

When true, will only match if the path matches the location.pathname exactly.如果为 true,则仅当路径与location.pathname完全匹配时才会匹配。

<Route exact path="/employees">
  <Employees />
</Route>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM