【问题标题】:React Component Rendering TwiceReact 组件渲染两次
【发布时间】:2019-05-26 19:32:38
【问题描述】:

正如标题所说,我的应用程序主页由于某种原因呈现两次,我不知道为什么。我最初从 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 文件?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    发生这种情况是因为您要渲染它两次,一次在 App 的顶层,另一次在 Route 组件内(当您访问 / 时)。

    const App = () => (
        <div>
            <HomePage /> {/* you are rendering it here */}
            <Route />    {/* you are also rendering HomePage within Route */}
        </div>
    )
    

    您需要决定是仅在访问/ 时显示HomePage,还是无论访问哪条路线都始终显示。

    对于前者,您应该从App 中删除HomePage

    const App = () => (
        <div>
            <Route />    {/* only render HomePage within Route, when / is visited */}
        </div>
    )
    

    对于后者,您应该从Route 中删除HomePage

    const Routes = () => (
        <main>
        <Switch>
            <Route exact path='/' component={() => 'Welcome to the home page'}/>
            <Route exact path='/projects' component={Projects}/>
        </Switch>
        </main>
    )
    

    【讨论】:

    • 谢谢你说得有道理,所以我可以在应用程序中取出那个吗?
    猜你喜欢
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多