因此,正如标题所述,由于某种原因,我的应用程序主页呈现了两次,但我不确定为什么。首先,我从BrowserRouter调用一个JS文件,然后从该位置调用HomePage组件和React Router,但随后我的页面呈现两次,我不确定为什么。
我的浏览器路由器(index.js):
import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import App from './App';
render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('root'));
然后将App.js称为:
const App = () => (
<div>
<HomePage />
<Route />
</div>
)
export default App;
然后是我的主页组件(index.jsx):
import React from 'react';
import { Link } from 'react-router-dom';
const HomePage = () => (
<html>
<ul><li>Home</li>
<Link to='/projects'><li>Projects</li></Link>
<li>Future Work</li>
<li>About Me</li>
</ul>
<title>A Peak Into My Life</title>
<h2>New Production Build</h2>
<body>
Projects Will Be Shown Here:
<body> This is the Flinder application: </body>
</html>
)
export default HomePage;
和Route.js:
const Routes = () => (
<main>
<Switch>
<Route exact path='/' component={HomePage}/>
<Route exact path='/projects' component={Projects}/>
</Switch>
</main>
)
但是随后我的页面呈现如下:
我真的很困惑,所以任何建议都会有所帮助!我猜可能有问题,因为我在路由中调用的是jsx文件而不是js文件?
答案 0 :(得分:4)
之所以发生这种情况,是因为您要渲染两次,一次是在App
的顶层,一次是在Route
组件中(当您访问/
时)。
const App = () => (
<div>
<HomePage /> {/* you are rendering it here */}
<Route /> {/* you are also rendering HomePage within Route */}
</div>
)
您需要决定只在访问HomePage
时显示/
,还是无论访问哪条路线都始终显示它。
对于前者,您应该从HomePage
中删除App
:
const App = () => (
<div>
<Route /> {/* only render HomePage within Route, when / is visited */}
</div>
)
对于后者,您应该从HomePage
中删除Route
:
const Routes = () => (
<main>
<Switch>
<Route exact path='/' component={() => 'Welcome to the home page'}/>
<Route exact path='/projects' component={Projects}/>
</Switch>
</main>
)