我是React的新手,我对React Router Dom有问题。 我正在开发一个单页应用程序,以便继续练习和 我有一个汉堡菜单,在其中使用“链接”来匹配良好的URL。我希望此链接加载关联的组件,但我必须刷新页面以加载所需的组件。
我阅读了很多解决此问题的方法,并尝试了其中的大多数方法,但是没有人帮助我解决问题。
此处是App.js:
import Formations from "./formations/formations";
import Experiences from "./experiences/experiences";
import BM from "./BM/BM";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
withRouter,
} from "react-router-dom";
class App extends React.Component {
render() {
return (
<div className="App">
<Header />
<p className="App-intro">{this.state.apiResponse}</p>
<Router>
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/formations" component={Formations} />
<Route path="/experiences" component={Experiences} />
</Switch>
</div>
</Router>
<div className="bottomPage">
<p>down page</p>
</div>
</div>
);
}
}
我的Burger Menu组件位于Header文件Header.js中:
import React from "react";
import "./Header.css";
import BM from "../BM/BM";
class Header extends React.Component {
render() {
return (
<div className="headerStyle">
<header>
<img src=""></img>
<p>GF</p>
<div id="outer-container">
<BM />
</div>
</header>
</div>
);
}
}
export default Header;
最后是我的汉堡菜单:
import React from "react";
import { pushRotate as Menu } from "react-burger-menu";
import { BrowserRouter as Router, Link, Route, Switch} from 'react-router-dom'
import "./BM-styles.css";
class BM extends React.Component {
render() {
return (
<Menu>
<Router>
<li><Link to="/" className="menu-item">
Home
</Link></li>
<p className="bar">/</p>
<li><Link to="/experiences" className="menu-item" >
Expériences
</Link></li>
<p className="bar">/</p>
<li><Link to="/formations" className="menu-item" >
Formations
</Link></li>
<p className="bar">/</p>
<li><Link to="/loisirs" className="menu-item">
Loisirs
</Link></li>
</Router>
</Menu>
);
}
}
export default BM;
我已经尝试使用“ withRouter()”,但是没有任何反应... 我认为这是因为链接必须紧挨交换机和路由器,但是我该怎么办? 如果有人可以帮助我:) 谢谢
答案 0 :(得分:0)
您应将<Header />
移至Router
,
class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<Header />
<p className="App-intro">API response</p>
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/formations" component={Formations} />
<Route path="/experiences" component={Experiences} />
</Switch>
</div>
</Router>
<div className="bottomPage">
<p>down page</p>
</div>
</div>
);
}
}
从<Router>
组件中删除BM
,
class BM extends React.Component {
render() {
return (
<Menu>
<li><Link to="/" className="menu-item">
Home
</Link></li>
<p className="bar">/</p>
<li><Link to="/experiences" className="menu-item" >
Expériences
</Link></li>
<p className="bar">/</p>
<li><Link to="/formations" className="menu-item" >
Formations
</Link></li>
<p className="bar">/</p>
<li><Link to="/loisirs" className="menu-item">
Loisirs
</Link></li>
</Menu>
);
}
}