使用 React Router 处理多个路由
Handling multiple routes with React Router
是否可以通过react router在一个视图中处理多个独立的路由?
就像拥有一个通过 /home
渲染的组件并通过 /contact
在模式中打开另一个视图并且由 /home
渲染的组件留在后台?
到目前为止我只管理了 1 个 "active" 组件。一旦我通过 /contact
打开我的模式,主页组件就消失了。
默认情况下,react-router
按照您呈现它们的顺序呈现所有匹配的路由。
所以,您想要的行为是默认行为:
<main>
<Route path="/" component={() => <h1>Home</h1>} />
<Route path="/1" component={() => <h2>Page 1</h2>} />
<Route path="/2" component={() => <h2>Page 2</h2>} />
</main>
在路由 "/1"
上面的代码将在第一条和第二条路由上渲染组件。
并且为了一次只呈现一条匹配的路线,我们需要使用 Switch
组件:
<main>
<Switch>
<Route path="/" component={() => <h1>Home</h1>} exact />
<Route path="/1" component={() => <h2>Page 1</h2>} />
<Route path="/2" component={() => <h2>Page 2</h2>} />
</Switch>
</main>
现在,在 "/1"
路线上,上面的代码将仅从第二条路线呈现组件。
exact
用于始终不匹配 "/"
。
这是完整的示例https://codesandbox.io/s/nnv800pxr4
此外,还有另一种方法可以实现这种行为 - 嵌套路由。只渲染子路由之外的其他东西,它会在任何子路由匹配时一直渲染:
// somewhere in routes
<Route path="/home" component={HomeComponent} />
// HomeComponent content
<div>
<h1>Some content<h1>
<h2>Rendered every time HomeComponent are rendered!</h2>
<Switch>
{/* some child routes */}
<Routes path="/contacts" component={ContactModal} />
{/* some child routes */}
</Switch>
</div>
请注意,目前 react-router@4
lacks good nested routes API。 IMO,在 react-router@3
这样的事情更容易实现。
是否可以通过react router在一个视图中处理多个独立的路由?
就像拥有一个通过 /home
渲染的组件并通过 /contact
在模式中打开另一个视图并且由 /home
渲染的组件留在后台?
到目前为止我只管理了 1 个 "active" 组件。一旦我通过 /contact
打开我的模式,主页组件就消失了。
默认情况下,react-router
按照您呈现它们的顺序呈现所有匹配的路由。
所以,您想要的行为是默认行为:
<main>
<Route path="/" component={() => <h1>Home</h1>} />
<Route path="/1" component={() => <h2>Page 1</h2>} />
<Route path="/2" component={() => <h2>Page 2</h2>} />
</main>
在路由 "/1"
上面的代码将在第一条和第二条路由上渲染组件。
并且为了一次只呈现一条匹配的路线,我们需要使用 Switch
组件:
<main>
<Switch>
<Route path="/" component={() => <h1>Home</h1>} exact />
<Route path="/1" component={() => <h2>Page 1</h2>} />
<Route path="/2" component={() => <h2>Page 2</h2>} />
</Switch>
</main>
现在,在 "/1"
路线上,上面的代码将仅从第二条路线呈现组件。
exact
用于始终不匹配 "/"
。
这是完整的示例https://codesandbox.io/s/nnv800pxr4
此外,还有另一种方法可以实现这种行为 - 嵌套路由。只渲染子路由之外的其他东西,它会在任何子路由匹配时一直渲染:
// somewhere in routes
<Route path="/home" component={HomeComponent} />
// HomeComponent content
<div>
<h1>Some content<h1>
<h2>Rendered every time HomeComponent are rendered!</h2>
<Switch>
{/* some child routes */}
<Routes path="/contacts" component={ContactModal} />
{/* some child routes */}
</Switch>
</div>
请注意,目前 react-router@4
lacks good nested routes API。 IMO,在 react-router@3
这样的事情更容易实现。