我正在尝试将路由分离到它们自己的文件中,但它们似乎总是被渲染,即使我已经exact
添加到path
中。
首页路线 -home.js
:
import React from 'react';
import { BrowserRouter as Route } from 'react-router-dom';
import { HomePageView } from 'components'
const HomeRoute = () => (
<Route exact path='/home'>
<HomePageContainer />
</Route>
)
export default HomeRoute;
首页浏览.js:
import React from 'react';
class HomePageView extends React.Component {
render() {
return (
<div>Some text here</div>
)
}
}
export default HomePageView;
索引.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import HomeRoute from 'routes/home'
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<Router>
<HomeRoute />
</Router>,
document.getElementById('root')
);
问题是它会在任何路径上呈现HomePageView
组件,我不明白为什么会发生这种情况,因为如果我将index.js
中的<HomeRoute />
替换为:
<Route exact path='/home'>
<HomePageContainer />
</Route>
我自己还没有测试过这个,但是您在家中将浏览器路由器作为路由导入不是问题吗.js?
渲染时,该文件将如下所示:
<BrowserRouter>
<BrowserRouter>
<HomePageContainer/>
<BrowserRouter/>
<BrowserRouter/>
您需要像这样从 react-router-rom 导入路由import { Route } from "react-router-dom";
导入中的"as"是别名,而不是导入的内容。
固定主页.js文件:
import React from 'react';
import { Route } from "react-router-dom";
import { HomePageView } from 'components'
const HomeRoute = () => (
<Route exact path='/home'>
<HomePageContainer />
</Route>
)
export default HomeRoute;