[英]React nested routing problem (cannot displayed the child component)
I am new to react development.我是反应开发的新手。 And I want to implement the routing mechanism in my page.
而且我想在我的页面中实现路由机制。 For example, there's component contains routes with the
<Home />
and <Login />
component.例如,有一个组件包含带有
<Home />
和<Login />
组件的路由。
function App() {
return (
<div className="App">
<Switch>
<Route exact path="/home">
<Home />
</Route>
<Route path="/login">
<Login />
</Route>
</Switch>
</div>
);
}
The <Home />
component contains a <Navbar />
and a <Switch />
with two <Route />
: <Home />
组件包含一个<Navbar />
和一个<Switch />
以及两个<Route />
:
Home.js主页.js
function Home() {
return (
<div>
<Navbar />
<div>
<Switch>
<Route exact path={`/home`}>
<Menu />
</Route>
<Route path={`/home/temperature`}>
<div>temperature</div>
</Route>
</Switch>
</div>
</div>
)
}
However, I defined the <Link />
in the <Menu />
component as below:但是,我在
<Menu />
组件中定义了<Link />
如下:
function Menu() {
return (
<div>
<li>
<Link to={`/home/temperature`}>temperature child page</Link>
</li>
</div>
)
}
Originally, the page would displayed the <Home />
component with <Menu />
and <div> temperature </div>
最初,页面会显示带有
<Menu />
和<div> temperature </div>
的<Home />
组件
I expected that when I clicked the link ( <Link to={
/home/temperature }>temperature child page</Link>
) then it would replace the <Menu />
component with the only the <div>temperature</div>
(Dispalyed the <Navbar/>
and <div>temperature</div>
, but it could not display anything.我希望当我点击链接(
<Link to={
/home/temperature }>temperature child page</Link>
)然后它会用唯一的<div>temperature</div>
替换<Menu />
组件(显示<Navbar/>
和<div>temperature</div>
,但它无法显示任何内容。
How should I correct it?我应该如何纠正它?
I finally figure out why I cannot get child component in my js script.我终于弄清楚为什么我无法在我的 js 脚本中获取子组件。
Firstly, I need to wrap the <Switch>
with <Router>
in <App>
component.首先,我需要在
<App>
组件中用<Router>
包装<Switch>
。 Then, by reference this , I realized that I should not specify the exact
in <Route path="/home">
to make sure that the nested route can work as well.然后,通过引用this ,我意识到我不应该在
<Route path="/home">
指定exact
以确保嵌套路由也可以工作。
function App() { return ( <div className="App"> <Router> <div> <Switch> <Route path="/home"> <Home /> </Route> <Route path="/login"> <Login /> </Route> </Switch> </div> </Router> </div> ); }
simple routing简单路由
<Router>
<Switch>
<Route path={"/home"} exact component={Home} />
</Switch>
</Router>
nested routing嵌套路由
<Router>
<Switch>
<Route path={"/home"} exact component={Home}
<Rout path={"/temperature"} exact component={Temperature} />
</Route>
</Switch>
</Router>
` `
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.