SyntaxError:预期与 react-router-dom v6 对应的 JSX 关闭标记 <Route>
2022-05-11
578
我希望我的 React 应用具有类似
localhost:3000/projects/construction
和
localhost:3000/services/landscape
的 URL。
react-router-dom 的 docs 文档说,你可以像这样嵌套路由:
function App() {
return (
<Routes>
<Route path="invoices" element={<Invoices />}>
<Route path="sent" element={<SentInvoices />} />
</Route>
</Routes>
);
}
那么,为什么当我执行此操作时,我的应用会失败并出现
Expected opposite JSX closing tag for <Route>
错误?
<BrowserRouter>
<Routes>
<Route index element={<Home />} />
<Route path='/projects' element={<Projects />}>
<Route path='/construction' element={<Construction />}>
</Route>
<Route path='/services' element={<Services />}>
<Route path='/landscape' element={<Landscape />}>
</Route>
<Route path='/about' element={<About />} />
<Route path='/contact' element={<Contact />} />
<Route path='*' element={<Navigate to='/' replace />} />
</Routes>
</BrowserRouter>
编辑:选定的答案说要关闭标签,这是正确的,但这会使所有页面呈现空白(除非我取消注释嵌套的路线)。
App.js
import Services from './components/Services.js'
import Landscape from './components/Landscape.js'
function App() {
return (
<BrowserRouter>
<Routes>
<Route index element={<Home />} />
<Route path='/services' element={<Services />}>
<Route path='/landscape' element={<Landscape />} />
</Route>
</Routes>
</BrowserRouter>
);
}
export default App;
Services.js
import { Outlet } from 'react-router-dom'
function Services() {
return (
<Container>
<Row>
<Col>Services</Col>
</Row>
<Outlet />
</Container>
);
}
export default Services;
1个回答
Services
和
Landscape
路线缺少结束标记。它们可以自行关闭,也可以添加结束标记。
<BrowserRouter>
<Routes>
<Route index element={<Home />} />
<Route path="/projects" element={<Projects />}>
<Route path="/construction" element={<Construction />}></Route>
<Route path="/services" element={<Services />} /> // <-- close
<Route path="/landscape" element={<Landscape />} /> // <-- close
</Route>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
Drew Reese
2022-05-11