我试图将路径分离到它们自己的文件中,但它们似乎总是被渲染,即使我添加了 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;
HomePageView.js。
import React from 'react';
class HomePageView extends React.Component {
render() {
return (
<div>Some text here</div>
)
}
}
export default HomePageView;
index.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
组件在任何路径上,我不明白为什么会发生这种情况,因为如果我替换了 <HomeRoute />
从 index.js
与。
<Route exact path='/home'>
<HomePageContainer />
</Route>
我自己没有测试过,但问题是不是在于你在home.js中把BrowserRouter导入为Route?
文件渲染后会是这个样子。
<BrowserRouter>
<BrowserRouter>
<HomePageContainer/>
<BrowserRouter/>
<BrowserRouter/>
你需要从react-router-rom中导入route,就像这样。import { Route } from "react-router-dom";
import中的 "as "是别名,不是导入的内容。
修正了home.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;