仅显示某些路由的组件 - React

Sal*_*Sal 4 reactjs

我正在 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>
   );
};
Run Code Online (Sandbox Code Playgroud)

Chr*_*Ngo 5

没错。按照目前的构造,您<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>
   );
};
Run Code Online (Sandbox Code Playgroud)

在我们的新Router定义中,Header组件将始终显示。这里重要的是理解Switch组件。它将呈现Route路径与提供的 URL 匹配的第一个。因此,如果 URL 是,"/"我们将仅显示HeaderLoginPage

但是,假设现在我们导航到 URL "/EventInfo"。现在,Switch在我们的 中定义的外部没有匹配路径Router,所以我们渲染AuthenticatedRoutes组件。执行相同的模式,现在我们NavigationBar始终显示react-router-dom并将执行内部Switch以查找Route其路径与提供的 URL 匹配的路径。因此也渲染EventInfo组件。

这种结构对于切换authenticatedunauthenticated组件的显示非常有用。


Sre*_*han 0

你可以这样做:

render() {
  return (
    <Router className="App">
      <Header />
      <div id="container">
        <Route path="/" exact component={LoginPage} />
        <Route path="/blah">
          <NavigationBar />
          <Route path="/blah/EventInfo" component={EventInfo} />
          <Route path="/blah/RSVP" component={RSVP} />
          <Route path="/blah/Attendance" component={Attendance} />
          <Route path="/blah/Confirmation" component={Confirmation} />
          <Route path="/blah/Contact" component={Contact} />
          <Route path="/blah/Lodging" component={Lodging} />
        </Route>
      </div>
    </Router>
  );
};
Run Code Online (Sandbox Code Playgroud)