reactjs - 如何将子目录与反应路由器一起使用?
问题描述
我是 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组件。
我究竟做错了什么?
解决方案
该Route
组件进行子字符串匹配,因此/employees/create
被/employees
路由匹配。将exact
prop 传递给Route
组件以确保仅在完全匹配时才渲染它。
从文档中,
exact
:bool
当为真时,只有当路径完全匹配时才会匹配
location.pathname
。
<Route exact path="/employees">
<Employees />
</Route>
推荐阅读
- azure - 停止 azure 流分析会停止成本计算吗?
- excel - 如何使用 VBA-excel 聚合不同的 word 文件?
- javascript - 是否可以修改 Set 中的值
- php - php 不断返回黑钻问号
- python - 如何在 Django 中使用 mysql 数据库数据到 FusionCharts
- javascript - 具有对象数组的深度展平嵌套数组
- android - 在用户触摸时关闭 FAB 子菜单
- sql-server - 如果我们需要 DAG 连接到 sql 服务器,要在气流环境的 docker 映像中添加什么?连接的代码是什么?
- python - 在 Colaboratory 中从 Google Drive 加载数据时遇到问题
- apache-flink - Apache flink - 早期触发窗口实现问题 - 收到重复的元素