我在我的应用程序中使用react-router进行程序导航。除了我想要添加的这个新功能之外,一切都很好,它需要条件路由。
我需要渲染,例如当location为/users/profile时为profileRoutes,当location为/users/details时为somethingElse。下面的代码现在运行得很好,因为我只构建了profileRoutes。但是我将路由合并为一个,并且需要/users/*或类似的东西,以便该位置将匹配与/users/相关的所有路由……
<Route
children={({ location }) => (
<div>
{
location.pathname === "/users/profiles" ?
<profileRoutes></profileRoutes> :
<otherComponent/>
}
</div>
)}
/>我的问题是:有没有一种react-router的方法来实现这一点?比如location.pathname.startswith....之类的东西?
发布于 2019-07-04 10:33:20
根据您的需求,请使用参数exact。
与/users /users/profiles 或/users或 /users/what-ever**:**匹配的
<Route path="/users" component={Users} />仅与 /users匹配的
<Route exact path="/users" component={Users} />原则上,让我们这样做:
exact的Route指向component Users中的component Users Route匹配main的子组件示例如下:
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
export function RouterExample() {
return (
<Router>
<div>
<ul>
<li>Main Menu:</li>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/users" component={Users} />
</div>
</Router>
);
}
function Home() {
return (
<div>
<h2>Welcome home</h2>
</div>
);
}
function Users({ match }) {
return (
<div>
<h2>Welcome to Users</h2>
<ul>
<li>Users menu:</li>
<li>
<Link to={`${match.url}/profiles`}>User Profiles</Link>
</li>
<li>
<Link to={`${match.url}/settings`}>User Settings</Link>
</li>
</ul>
<Route exact path={`${match.path}`} component={UserHome} />
<Route path={`${match.path}/profiles`} component={UserProfiles} />
<Route path={`${match.path}/settings`} component={UserSettings} />
<Route path={`${match.path}/:section`} component={UserFooter} />
</div>
);
}
function UserHome() {
return (
<div>
<h3>UserHome Component</h3>
</div>
);
}
function UserProfiles() {
return (
<div>
<h3>UserProfiles Component</h3>
</div>
);
}
function UserSettings() {
return (
<div>
<h3>UserSettings Component</h3>
</div>
);
}
function UserFooter({ match }) {
return (
<div>
<hr />
UserFooter Component is always visible under /users/*
<br />
You are now at
<br />
path: {match.path}
<br />
match params: {match.params.section}
</div>
);
}
在codesandbox上进行现场演示
发布于 2019-07-11 06:22:39
感谢你给我指明了正确的方向,即使用match!我不需要修改我的路由(我喜欢把我的组件分开,只需要导入。我确实在根组件/上有一个确切的标记。以下是对我有效的方法:
<Route
children={({ match }) => (
<div>
{
match.path == "/users" ?
<profileRoutes></profileRoutes> :
<otherComponent/>
}
</div>
)}
/>现在当match.path == "/users"为true时,所有下游的路由即/users/etc都会被渲染。希望这对其他人有帮助!
https://stackoverflow.com/questions/56879179
复制相似问题