我今天的问题是我正在使用react-router-dom并在AppRouter.js中设置所有路径:
import React, { Component } from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import { Landing } from '../components/Landing';
import About from '../components/About';
import { Resume } from '../components/Resume';
import { Phone } from '../components/Phone';
import { Github } from '../components/Github';
export class AppRouter extends Component {
render() {
return (
<BrowserRouter>
<div>
<Switch>
<Route exact path='/' Component={Landing}/>
<Route path='/about' Component={About} />
<Route path='/resume' Component={Resume} />
<Route path='/phone' Component={Phone} />
<Route path='/github' Component={Github} />
</Switch>
</div>
</BrowserRouter>
)
}
}
export default AppRouter
现在,当我在NavBar组件中使用NavLink时,URL会更改为路径,但不会将组件呈现到屏幕上。
NavBar组件:
import React, { Component } from 'react';
import {NavLink} from 'react-router-dom';
export class Navbar extends Component {
render() {
return (
<div>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="#">"IMAGE PLACE HOLDER"
</a>
<button className="navbar-toggler" type="button" data-
toggle="collapse" data-target="#navbarNavDropdown" aria-
controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle
navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse"
id="navbarNavDropdown">
<ul className="navbar-nav">
<li className="nav-item active">
<NavLink className='nav-link' to='/'>Home</NavLink>
</li>
<li className="nav-item">
<a className="nav-link" href="#">Resume</a>
</li>
<li className="nav-item">
<NavLink className='nav-link'
to='/about'>About</NavLink>
</li>
<li className="nav-item dropdown">
<a className="nav-link dropdown-toggle" href="#"
id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-
haspopup="true" aria-expanded="false">
Contact
</a>
<div className="dropdown-menu" aria-
labelledby="navbarDropdownMenuLink">
<a className="dropdown-item" href="#">Phone</a>
<a className="dropdown-item" href="#">Email</a>
<a className="dropdown-item" href="#">Github</a>
</div>
</li>
</ul>
</div>
</nav>
</div>
)
}
}
export default Navbar
AppRouter->登陆->导航栏和标题
NavBar不是AppRouter的直接子代,但从Landing继承。但是,我确实将其更改为NavBar是AppRouter的直接子项,但这并没有改变Landing组件未在页面的初始加载时呈现的事实。
答案 0 :(得分:0)
以防万一其他人正在为这个问题而苦苦挣扎。
就我而言,该应用是在顶层封装<BrowserRouter>
并在较低级别(NavLinks旁边)封装。删除第二个BrowserRouter即可解决。
答案 1 :(得分:0)
在将 react 升级到 17.x 并将 react-router-dom 升级到 5.x 时,我遇到了同样的问题。
我通过更改 <Router>
的 <BrowserRouter>
包装器修复了它。
<BrowserRouter>
<App />
</BrowserRouter>