问题
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