首页 > 解决方案 > 如何将子目录与反应路由器一起使用?

问题描述

我是 React 的新手,并试图了解路由,特别是如何使用 URL 路径中的子目录。

这是我的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

我在使用/employees/create路径时遇到问题。它正在加载Employees组件而不是EmployeesCreate组件。

我究竟做错了什么?

标签: reactjs

解决方案


Route组件进行子字符串匹配,因此/employees/create/employees路由匹配。将exactprop 传递给Route组件以确保仅在完全匹配时才渲染它。

文档中,

exactbool

当为真时,只有当路径完全匹配时才会匹配location.pathname

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

推荐阅读