重定向到 404 页面无法正常工作

时间:2021-02-15 12:55:59

标签: reactjs react-router react-router-dom

我有一个使用 react-router-dom 的带有一些路由的 React 应用程序。我正确地描述了我的路线,然后我写道,当 url 是 /**/ 重定向到 404 页面时; 这是我的路线:

    <Router>
      <Switch>
         <Route exact path="/" component={HomePage} />

         // my other routes
    
         <Route path="/404" component={NotFoundPage} />
         <Redirect from="/**/" to="/404" />
      </Switch>
    </Router>

当我转到其他页面时,它们可以正确显示,没有任何问题,当我在浏览器中写入错误的 url 时,它会重定向到 /404 地址并正常工作,但是当我想使用 "/" url 访问我的主页时,它的地址将我重定向到“/404”网址;我不知道我的问题出在哪里

3 个答案:

答案 0 :(得分:1)

    <Router>
      <Switch>
       <Route exact path="/" component={HomePage} />
       <Route path="/404" component={NotFoundPage} />

       // other routes

       <Redirect to="/404" />
      </Switch>
   </Router>

答案 1 :(得分:0)

"/" url 重定向到 "/404" url 的原因是因为这个路由:

<Redirect from="/**/" to="/404" />

要处理 404 路由,只需像这样编写路由:

<Router>
      <Switch>
         <Route exact path="/" component={HomePage} />

         // other routes

         <Route component={NotFoundPage} />
      </Switch>
</Router>

答案 2 :(得分:0)

当你想重定向所有不匹配的东西时,你应该省略 from 属性,所以你应该把它写在 Switch 的底部,如下所示:

<Redirect to="/404" />

它适用于版本 ^5