簡體   English   中英

ReactJs 中的路由器

[英]Router In ReactJs

我對 React Js 還很陌生,並且遇到了一個問題。 Root 組件下有 3 個組件,我想要做的是單擊我試圖顯示另一個組件的三個組件中的任何一個。 但問題在於單擊所需的組件已加載,但其他組件仍保留在頁面上。 請建議這里需要做什么。

    <div className="App">
      <Navbar />
     <Router>
      <div className="container" style={{ marginTop: '20px' }}>
      <div className="row">
        <div className="col s4">
          <AddCustomer />
        </div>
        <div className="col s4">
          <Switch>
            <Route exact path="/viewcustomers" component={ViewCustomer} />
          </Switch>
        </div>
        <div className="col s2 offset-s1">
          <Notifications />
        </div>
        </div>
         <div className="row">
        <div className="col s4">
          < EditCustomer />
         </div>
        </div>
       </div>
      </Router>
       </div>

這里轉到路徑 ViewCustomer 已加載,但其他組件仍然存在。 我當時只想展示一個組件。

干得好。 您應該使用RouterRoute組件來為每個視圖/頁面呈現組件。 react-router-dom庫中的Link組件應該用於在視圖之間導航。 我還建議從Router組件中分離出大部分 HTML。

const App = () => (
  <div className="App">
    <Navbar />
       <Router>
         <Switch>
           <Route component={HomeView} exact path='/' />
           <Route component={CustomerView} exact path='/viewcustomers' />
         </Switch>
    </Router>
  </div>
);

// Component to render when at '/'
const HomeView = () => {
  return (
    <div className="container" style={{ marginTop: '20px' }}>
      <div className="row">
        <div className="col s4">
          <AddCustomer />
        </div>
        <div className="col s4">
          <Link to='/viewcustomers' />
        </div>
        <div className="col s2 offset-s1">
          <Notifications />
        </div>
        </div>
         <div className="row">
        <div className="col s4">
          <EditCustomer />
        </div>
      </div>
    </div>
  );
};

// Component to render when at '/viewcustomers'
const CustomerView = () => {
  // Create customer view here
  return 'customers';
};

伙計,你對反應路由器的理解都搞砸了。 您的代碼的問題在於其他組件( <AddCustomer /><EditCustomer /> )在 Switch 之外並且沒有標記到任何 URL 模式,因此呈現在您所在的 URL 路徑中。

您的代碼應如下所示:

    <BrowserRouter>
        <div className="App">
            <Navbar />
            <Switch>
                <Route exact path="/addcustomers" component={AddCustomer} />
                <Route exact path="/viewcustomers" component={ViewCustomer} />
                <Route exact path="/editcustomers" component={EditCustomer} />
            </Switch>
        </div>
    </BrowserRouter>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM