2017-10-10 189 views
1

我正在学习React路由器。以下是使用Route时出现的问题。React路由器不匹配

const OPSTIONS = [ 
 
\t { 
 
\t \t name: "home", 
 
\t \t path: "/", 
 
\t \t main:() => <h1>Home</h1>, 
 
\t \t sidebar:() => <h1>Home</h1> 
 
\t }, 
 
\t { 
 
\t \t name: "mike", 
 
\t \t path: "/mike", 
 
\t \t main:() => <h2>mike</h2>, 
 
\t \t sidebar:() => <h3>mike</h3> 
 
\t }, 
 
\t { 
 
\t \t name: "jerry", 
 
\t \t path: "/jerry", 
 
\t \t main:() => <h2>jerry</h2>, 
 
\t \t sidebar:() => <h3>jerry</h3> 
 
\t }, 
 
\t { 
 
\t \t name: "jim", 
 
\t \t path: "/jim", 
 
\t \t main:() => <h2>jim</h2>, 
 
\t \t sidebar:() => <h3>jim</h3> 
 
\t }, 
 
] 
 

 
ReactDOM.render(
 
\t <Router> 
 
\t \t <div> 
 
\t \t \t <ul> 
 
\t \t \t \t {OPSTIONS.map(function(e, index) { 
 
\t \t \t \t \t return <li key={index}><Link to={e.path}>{e.name}</Link></li> 
 
\t \t \t \t })} 
 
\t \t \t </ul> 
 
\t \t </div> 
 
\t </Router>, 
 
\t document.getElementById("left") 
 
); 
 

 
ReactDOM.render(
 
\t <Router> 
 
\t \t <div> 
 
\t \t \t {OPSTIONS.map(function(e, index) { 
 
\t \t \t \t return <Route exact key={index} path={e.path} component={e.main}></Route> 
 
\t \t \t })} 
 
\t \t </div> 
 
\t </Router>, 
 
\t 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>
enter image description here

和路由器总是与主路线,无论什么我更改URL,该组件总是显示“家”,我都做什么了吗?我该如何解决它?

这是我的反应和应对路由器版本:

"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

我正在使用react v15.6.1和react-router v4.2.0和react-router-dom v4.2.2 – DongShelton

回答

0

您应该使用Switch将它包裹所有Route只渲染第一个匹配的组件。

<Router> 
    <Switch> 
     {OPSTIONS.map(function(e, index) { 
      return <Route exact key={index} path={e.path} component={e.main}></Route> 
     })} 
    </Switch> 
</Router> 

您可以阅读https://reacttraining.com/react-router/web/api/Switch

+0

我已经使用来包装它,它也不起作用 – DongShelton