首页 > 解决方案 > React Router v6 不会使用浏览器 URL 渲染/同步特定路由

问题描述

我有一些这样配置的路由:

<Router>
  <Routes>
    <Route path="/" element={<Home />} />

    <Route path="/about" element={<About />} />

    <Route path="/contact" element={<Contact />} />
  </Routes>
</Router>

问题是当我打开时/,转到/about然后转到/contact;URL 变为/about/contactand not /contact,除了页面未呈现。如何修复它,我使用的是6.0.0-Alpha-3版本。我已阅读此版本的文档,并且知道斜杠/contact表示绝对路径而不是相对路径contact

链接:

import { Link } from 'react-router-dom';

const ListItemLink = (props) => {
    // React Router link
    return <ListItem button component={Link} {...props} />;
};

// Material UI components
<ListItemLink href="/about">
    <ListItemText primary="Home" />
</ListItemLink>

<ListItemLink href="/contact">
    <ListItemText primary="Home" />
</ListItemLink>

标签: reactjsreact-router

解决方案


您必须使用 to 而不是 href 道具。

这是示例https://github.com/smkamranqadri/react-router-v6-test


推荐阅读