【问题标题】:React router 'Page Not Found' page not showing when Routes defined inside div当在 div 中定义路由时,反应路由器“未找到页面”页面未显示
【发布时间】:2019-04-03 09:47:36
【问题描述】:

我有一些添加了 header、div 和 sidemenu 的路由。 在这些之外,我添加了“找不到页面”路线。但是当我点击无效的 URL 时,它没有显示“未找到页面”页面

我尝试将所有路由放在“div”内,但我不需要“找不到页面”页面的这些 div、标题、侧边菜单

<Switch>
            <Route path="/" exact component={LoginPage} />
            <Route path="/ShowReport" component={ShowReport} />

            <div className="container-fluid py-5">
              <Header />
              <Notify />
              <div className="row justify-content-center pt-2">
                <Sidemenu />
                <Route path="/test" component={Test} />
                <Route path="/home" component={HomePage} />
              </div>
            </div>
            <Route component={NotFoundPage} />
          </Switch>

预期的结果是:当我点击无效的 URL 时,应该显示找不到没有标题的页面,sidemnu。

【问题讨论】:

    标签: javascript reactjs react-router-dom


    【解决方案1】:

    你用错了。试试这个方法:

    // import 
    import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
    
    // your class's return
    return (
        <Router>
          <Switch>
            <Route path="/" exact component={LoginPage} />
            <Route path="/ShowReport" component={ShowReport} />
    
            <div className="container-fluid py-5">
              <Header />
              <Notify />
              <div className="row justify-content-center pt-2">
                <Sidemenu />
                <Route path="/test" component={Test} />
                <Route path="/home" component={HomePage} />
              </div>
            </div>
            <Route component={NotFoundPage} />
           </Switch>
        </Router>
      );

    【讨论】:

    • 更改显示 NotFoundPage 的结构。
    【解决方案2】:

    我已经在沙盒中尝试了您的示例:https://reacttraining.com/react-router/web/example/basic 并得到了Invariant failed: You should not use &lt;Switch&gt; outside a &lt;Router&gt; 错误。

    尝试用Router 包装你的Switch,如下所示:

    import { BrowserRouter as Router } from 'react-router-dom';
    

    【讨论】:

      【解决方案3】:

      routing a No-Match 的主要示例中,Switch 元素被包裹在 Router 元素中,如下所示:

       <Router>
           <Switch>
                  <Route path="/" exact component={LoginPage} />
                  <Route path="/ShowReport" component={ShowReport} />
                  <Route component={NotFoundPage} />
           </Switch>
       </Router>
      

      如果这仍然不能解决您的问题,请尝试在 div 上方临时粘贴 &lt;Route component={NotFoundPage} /&gt;,这是否仍然显示空白页面或这是否会改变任何内容。

      如果这导致出现 notfoundpage,则您在原始代码中传递了一个未知的道具(可能通过传递样式?)。

      【讨论】:

        猜你喜欢
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 2017-08-13
        • 2018-06-26
        • 2019-02-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多