React Router component rendering twice

纵然是瞬间 提交于 2019-12-11 06:12:59

问题


I have a navigation bar component that I am trying to put together, and I have a problem in my App.js, where I call all the components. I have to render the navbar twice in order for it to work, but it shows up twice, where only the second navbar is functional. Taking out either of the 2 lines of code in the render results in an error, where only the text of the navbar shows up (but only shows up once, not twice), and is not clickable.

Here is render() with navbar rendered twice:

render() {
    return (
      <div>
        <Login />
        <Search />
        <BrowserRouter> 
            <div className='container'>
                <Navbar />
                <Route component={Navbar}/>
                <Route exact path="/" component={Home}/>
                <Route path="/bios" component={Bios}/>
                <Route path="/message" component={Message}/>
            </div>
        </BrowserRouter>
      </div>

    );
  }


回答1:


You may want the NavBar outside of your <BrowserRouter> as I'm guessing it is always rendered and not dependent on matching some route, i.e.

render() {
    return (
      <div>
        <Login />
        <Search />
        <Navbar />
        <BrowserRouter> 
            <div className='container'>
                <Route exact path="/" component={Home}/>
                <Route path="/bios" component={Bios}/>
                <Route path="/message" component={Message}/>
            </div>
        </BrowserRouter>
      </div>
    );
  }



回答2:


I fixed the problem. The error I was getting earlier was because the 2 statements below:

<Navbar />
    <Route component={Navbar}/>

One of them was rendering over another component, and apparently if two components overlap, even partially, the functionality of it disappears. I couldn't even tell that it overlapped because there was transparent padding around the components. All I did to fix it was delete the 2nd statement and style the navbar in my CSS so that it didn't overlap anymore.



来源:https://stackoverflow.com/questions/45269961/react-router-component-rendering-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!