[英]Router: No routes matched location "/" error react-router-dom v6
我最近从react-router-dom V5 to v6
,我收到以下消息:
index.js:44 No routes matched location "/"
这是我的 App 组件的外观
const joinedSignupRoutes = `/(${allSteps
.map((step) => step.path.substr(1))
.join('|')})`;
const App = ({ history }) => {
return (
<ConnectedRouter history={history}>
<Routes>
<Route path={joinedSignupRoutes} element={<RegistrationRoutes />} />
任何关于如何解决这个问题的想法将不胜感激。
为路径"/"
添加一个路由,因为它丢失了。
例子:
const joinedSignupRoutes = `/(${allSteps
.map((step) => step.path.substr(1))
.join('|')})`;
const App = ({ history }) => {
return (
<ConnectedRouter history={history}>
<Routes>
<Route path="/" element={<h1>Home</h1>} /> // <-- replace with actual component
<Route path={joinedSignupRoutes} element={<RegistrationRoutes />} />
</Routes>
</ConnectedRouter>
);
};
...而不是
<Route path="/" element={<h1>Home</h1>} />
作为登陆页面我想要<Route path={joinedSignupRoutes} element={<RegistrationRoutes />} />
。 即App运行时第一个看到的页面应该是RegistrationRoutes组件。
您仍然需要在路径"/"
上渲染路由以维护react-router-dom@6
强制执行的不变量,但您可以在该路由上渲染任何内容。 在这种情况下,您可以呈现重定向到您的joinedSignupRoutes
路由。
例子:
import { ...., Navigate } from 'react-router-dom';
const joinedSignupRoutes = `/(${allSteps
.map((step) => step.path.substr(1))
.join('|')})`;
const App = ({ history }) => {
return (
<ConnectedRouter history={history}>
<Routes>
<Route
path="/"
element={<Navigate to={joinedSignupRoutes} replace />}
/>
<Route path={joinedSignupRoutes} element={<RegistrationRoutes />} />
</Routes>
</ConnectedRouter>
);
};
// Joins all signup paths to a singel route to multimatch it against. // eg. path="/(step-1|step-2|step-3)" const joinedSignupRoutes = `/(${allSteps.map((step) => step.path.substr(1)).join("|")})`;
react-router-dom@5
路由可以采用使用正则表达式的path
道具。 在react-router-dom@6
中不是这种情况。
正则表达式路由路径被删除有两个原因:
路由中的正则表达式路径对 v6 的排名路由匹配提出了很多问题。 您如何对正则表达式进行排名?
我们能够摆脱整个依赖关系(正则表达式路径)并显着减少发送到用户浏览器的 package 权重。 如果加回来,就代表了 React Router 页面权重的 1/3!
在查看了很多用例之后,我们发现在没有直接正则表达式路径支持的情况下我们仍然可以满足它们,因此我们做出权衡以显着减小包大小并避免围绕正则表达式路由排名的开放性问题。
大多数正则表达式路由一次只关注一个 URL 段,并做以下两件事之一:
- 匹配多个 static 值
- 以某种方式验证参数(是数字,不是数字等)
要在 v6 中处理此问题,您需要为每条路径指定一个显式路由。 从"/"
重定向到"/step-1"
例子:
import { ...., Navigate } from 'react-router-dom';
const joinedSignupRoutes = `/(${allSteps
.map((step) => step.path.substr(1))
.join('|')})`;
const App = ({ history }) => {
return (
<ConnectedRouter history={history}>
<Routes>
<Route
path="/"
element={<Navigate to={allSteps[0]} replace />}
/>
{allSteps.map(path => (
<Route
key={path}
path={path}
element={<RegistrationRoutes />}
/>
))}
</Routes>
</ConnectedRouter>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.