react-router v4 路径匹配时,比如/reactpage,也会匹配到/根路径?
react-router v4 路径匹配时,比如/reactpage,也会匹配到/根路径?
代码:
// react-router.js
import React, { Component } from 'react'
import { Router, Route } from 'react-router-dom'
import { createBrowserHistory } from 'history'
import ReactPage from './reactPage'
import ReduxPage from './reduxPage'
import RouterPage from './routerPage'
import HomePage from './homePage'
const routes = [
{
path: '/',
component: HomePage,
},
{
path: '/reactpage',
component: ReactPage,
},
{
path: '/reduxpage',
component: ReduxPage,
},
{
path: '/routerpage',
component: RouterPage,
},
]
const history = createBrowserHistory()
const RouteWithSubRoutes = (route) => (
<Route path={route.path} render={props => (
<route.component {...props} />
)}/>
)
export default class App extends Component {
render() {
return (
<Router history={history}>
<div>
{
routes.map((route, i) => (
<RouteWithSubRoutes key={i} {...route} />
))
}
</div>
</Router>
)
}
}
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import App from './react-router'
import { store } from './redux/store'
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root')
)
// homePage
import React, { Component } from 'react'
export default class HomePage extends Component {
render() {
return (
<h1>这是HomePage</h1>
)
}
}
// reactPage.js
import React, { Component } from 'react'
export default class ReactPage extends Component {
render() {
return (
<h1>这是ReactPage</h1>
)
}
}
效果图
当匹配/reactpage的时候,把/路径下的homePage也渲染出来了。 react-router v3是没这个问题。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问了个很二的问题,找到了原因了,是因为没加exact,RouteWithSubRoutes改成如下:
关键是v3中好像我也没加exact也没事。。
建议你看下react-route 4.0 官方文档中 exact 和 strict 的用法
https://reacttraining.com/rea...