2017-10-10 224 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