我正在 React 中开发一个带有登录界面的网站。该网站显示一个自定义导航组件,但是我不希望它显示在主路线(即登录页面)上,但据我了解,静态组件不会在路线更改时重新呈现,这准确吗?
我正在使用 React-Router 来处理所有路由。
这是我的 App.js 现在的样子:
render() {
return (
<Router className="App">
<Header />
<NavigationBar />
<div id="container">
<Route path="/" exact component={LoginPage}/>
<Route path="/EventInfo" component={EventInfo}/>
<Route path="/RSVP" component={RSVP}/>
<Route path="/Attendance" component={Attendance}/>
<Route path="/Confirmation" component={Confirmation}/>
<Route path="/Contact" component={Contact}/>
<Route path="/Lodging" component={Lodging}/>
</div>
</Router>
);
};
这是正确的。按照目前的构造,您的<NavigationBar />
会一直显示。你能做的就是隔离Routes
使用 NavigationBar 到自己的组件。
所以尝试这样的事情:
import { Switch, Router, Route } from "react-router-dom"; // fixed "
render() {
const AuthenticatedRoutes = () => {
return (
<NavigationBar />
<div id="container">
<Switch>
<Route path="/EventInfo" component={EventInfo}/>
<Route path="/RSVP" component={RSVP}/>
<Route path="/Attendance" component={Attendance}/>
<Route path="/Confirmation" component={Confirmation}/>
<Route path="/Contact" component={Contact}/>
<Route path="/Lodging" component={Lodging}/>
</Switch>
</div>
)
}
return (
<Router className="App">
<Header />
<Switch>
<Route path="/" exact component={LoginPage}/>
<Route component={AuthenticatedRoutes}/>
</Switch>
</Router>
);
};
在我们的新Router
定义,将Header
组件将始终显示。
这里重要的是要理解Switch
成分。它将渲染第一个Route
其路径与提供的 URL 匹配。所以如果网址是"/"
我们将只显示Header
and LoginPage
.
但是,假设现在我们导航到 URL"/EventInfo"
。现在,外部没有匹配的路径Switch
定义在我们的Router
,所以我们渲染AuthenticatedRoutes
成分。执行相同的模式,现在我们显示NavigationBar
在任何时候和react-router-dom
将执行内部Switch
找到一个Route
其路径与提供的 URL 匹配。从而渲染出EventInfo
组件也是如此。
这个结构对于切换显示非常有用authenticated
and unauthenticated
成分。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)