简体   繁体   English

ReactJS 中的错误页面呈现在每个页面组件下方

[英]Error Page in ReactJS is rendered below every single page component

I managed to create a website for myself using ReactJS.我设法使用 ReactJS 为自己创建了一个网站。 Everything works fine except that my last addition of an Error Page turns out that is rendered underneath every other page that is rendered.一切正常,除了我最后添加的错误页面结果显示在所有其他渲染页面的下方。 Ie if I go to /localhost:3000/blog where all the blog elements are rendered, underneath this and above footer the Error404 component is also rendered.即,如果我将 go 到呈现所有博客元素的 /localhost:3000/blog ,则在此页脚下方和页脚上方也会呈现 Error404 组件。 Any advice so I can expand my so far limited knowledge?有什么建议可以扩展我迄今为止有限的知识吗? The app component is this:应用程序组件是这样的:

const App = () => {
  return (
    <Router>
      <Switch>

        <Route exact path="/">
          <Home />
        </Route>
      
          <div className="appWrapper">
            <NavBar />


              <Route exact path="/blog">
                  <Blog />
              </Route>

              <Route exact path="/article/:id">
                        <Article />
                    </Route>

              <Route exact path="/contact">
                <ContactForm />
              </Route>
              
              <Route path="*">
                <Error404 />
              </Route>
              
            <Footer />
          </div>

      </Switch>
    </Router>
    
  )
}

You need to add another Switch wrapping your Route's to make sure only one Route will render at a time.您需要添加另一个Switch包装您的 Route,以确保一次只渲染一个 Route。

const App = () => {
  return (
    <Router>
      <Switch>

        <Route exact path="/">
          <Home />
        </Route>
      
          <div className="appWrapper">
            <NavBar />
              <Switch>
              <Route exact path="/blog">
                  <Blog />
              </Route>

              <Route exact path="/article/:id">
                        <Article />
                    </Route>

              <Route exact path="/contact">
                <ContactForm />
              </Route>
              
              <Route path="*">
                <Error404 />
              </Route>
              </Switch>
            <Footer />
          </div>

      </Switch>
    </Router>
    
  )
}

Here is a working example .这是一个工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM