来自另一个文件的React路由在每个路径上都会被呈现出来

问题描述 投票:0回答:1

我试图将路径分离到它们自己的文件中,但它们似乎总是被渲染,即使我添加了 exactpath.

母线---- 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>
javascript reactjs path react-router url-routing
1个回答
1
投票

我自己没有测试过,但问题是不是在于你在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;
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.