网站仅在重新加载后更改-反应路由器

我想制作一个导航栏,其中包含指向不同路线的不同链接。在另一个文件中,我有react-router的东西以便更改网站。但是,当我按链接时,它是有效的,但前提是我事后重新加载。

头文件:

export default function Head(props){
    return(
        <Router>            
            <div className="Head">                      
                <div className="HeadItemFirst">bwftp</div>         
                <div className="HeadPaths">                    
                    <Link className="HeadItem" to="/"><div>Start</div></Link>
                    <Link className="HeadItem" to="/about"><div>about</div></Link>
                    <Link className="HeadItem" to="/settings"><div>Settings</div></Link>                        
                </div>                                 
            </div>             
        </Router> 
    )
}

和App文件:

export default function App(){
   return(
  <div className="App">
  <Head />{/* Here are all the links in a navbar stored */}      
  <Body /> 
  <Foot />

  <Router>         
    <Switch>
      <Route path="/" exact component={Home}/>
      <Route path="/about" exact component={About}/>
      <Route path="/settings" exact component={Settings}/>
      <Route render={()=>(<h1>404</h1>)}/>
    </Switch>
  </Router>
</div>
  )
}
评论
  • 灵凡
    灵凡 回复

    You need not use multiple router instances in your Application. Instead have one at the topmost parent level. If you use multiple Routes, the Link components inside Head will communicate with the Router component inside Head only and will not relay the information of route change to Router in App

    另外,如果将Head渲染为默认路线,它将从Route接收所有道具,并确保Routes的顺畅运行

    export default function Head(props){
        return(
            <div className="Head">                      
                <div className="HeadItemFirst">bwftp</div>         
                <div className="HeadPaths">                    
                    <Link className="HeadItem" to="/"><div>Start</div></Link>
                    <Link className="HeadItem" to="/about"><div>about</div></Link>
                    <Link className="HeadItem" to="/settings"><div>Settings</div></Link>                        
                </div>                                 
            </div>             
        )
    }
    
    
    export default function App(){
       return(
          <Router>
            <div className="App">
              <Route component={Head} />    //Render as a default route so that it gets route params
              <Body /> 
              <Foot />         
              <Switch>
                <Route path="/" exact component={Home}/>
                <Route path="/about" exact component={About}/>
                <Route path="/settings" exact component={Settings}/>
                <Route render={()=>(<h1>404</h1>)}/>
              </Switch>
            </div>
          </Router>
      )
    }