我正在学习React Router。使用Route时,以下是一个问题。
const OPSTIONS = [
{
name: "home",
path: "/",
main: () => <h1>Home</h1>,
sidebar: () => <h1>Home</h1>
},
{
name: "mike",
path: "/mike",
main: () => <h2>mike</h2>,
sidebar: () => <h3>mike</h3>
},
{
name: "jerry",
path: "/jerry",
main: () => <h2>jerry</h2>,
sidebar: () => <h3>jerry</h3>
},
{
name: "jim",
path: "/jim",
main: () => <h2>jim</h2>,
sidebar: () => <h3>jim</h3>
},
]
ReactDOM.render(
<Router>
<div>
<ul>
{OPSTIONS.map(function(e, index) {
return <li key={index}><Link to={e.path}>{e.name}</Link></li>
})}
</ul>
</div>
</Router>,
document.getElementById("left")
);
ReactDOM.render(
<Router>
<div>
{OPSTIONS.map(function(e, index) {
return <Route exact key={index} path={e.path} component={e.main}></Route>
})}
</div>
</Router>,
document.getElementById("main")
)
<div id="header"></div>
<div id="container">
<div id="main"></div>
<div id="left"></div>
<div id="right"></div>
</div>
<div id="footer"></div>
路由器总是匹配Home Route,无论我更改url,组件总是显示“Home”,我做错了什么?我该如何解决?
这是我的反应和反应路由器版本:
"devDependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-hot-loader": "^1.3.1",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
}
答案 0 :(得分:0)
您应该使用Switch
将Route
包裹起来,仅渲染第一个匹配的组件。
<Router>
<Switch>
{OPSTIONS.map(function(e, index) {
return <Route exact key={index} path={e.path} component={e.main}></Route>
})}
</Switch>
</Router>
中详细了解相关信息