来自另一个文件的 React 路由在每个路径上呈现
React route from another file is rendered on every path
我试图将路由分离到它们自己的文件中,但它们似乎总是被渲染,即使我已经将 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
组件,我不明白为什么会发生这种情况,因为如果我将 index.js
中的 <HomeRoute />
替换为:
<Route exact path='/home'>
<HomePageContainer />
</Route>
我自己还没有测试过,但这不是您在 home.js 中将 BrowserRouter 作为 Route 导入的问题吗?
渲染后的文件如下所示:
<BrowserRouter>
<BrowserRouter>
<HomePageContainer/>
<BrowserRouter/>
<BrowserRouter/>
你需要像这样从react-router-rom导入路由import { Route } from "react-router-dom";
"as" in import 是别名,不是导入的东西
已修复 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;
我试图将路由分离到它们自己的文件中,但它们似乎总是被渲染,即使我已经将 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
组件,我不明白为什么会发生这种情况,因为如果我将 index.js
中的 <HomeRoute />
替换为:
<Route exact path='/home'>
<HomePageContainer />
</Route>
我自己还没有测试过,但这不是您在 home.js 中将 BrowserRouter 作为 Route 导入的问题吗?
渲染后的文件如下所示:
<BrowserRouter>
<BrowserRouter>
<HomePageContainer/>
<BrowserRouter/>
<BrowserRouter/>
你需要像这样从react-router-rom导入路由import { Route } from "react-router-dom";
"as" in import 是别名,不是导入的东西
已修复 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;