简体   繁体   English

React 路由器 dom 没有渲染组件

[英]React router dom is not rendering a component

This is my code这是我的代码

function App() {
  return (
    <div className="app">
      <BrowserRouter>
        <Header></Header>
        <Routes>
          <Route path='/' exact element={<Home />} />
          <Route path='/movie/:imdbID' element={<MovieDetails />} />
          <Route element={<PageNotFound />} />
        </Routes>
        <Footer />
      </BrowserRouter>
    </div>
  );
}

What I want is for PageNotFound to be shown when I enter an invalid url.我想要的是当我输入无效的PageNotFound时显示 PageNotFound。 But it never shows up.但它永远不会出现。 I tried putting it at the top, after the <Routes> but same result.我尝试将它放在顶部,在<Routes>之后,但结果相同。

You can add the * to the path and it will render.您可以将*添加到路径中,它将呈现。

function App() {
  return (
    <div className="app">
      <BrowserRouter>
        <Header></Header>
        <Routes>
          <Route path='/' exact element={<Home />} />
          <Route path='/movie/:imdbID' element={<MovieDetails />} />
          <Route exact path='*' element={<PageNotFound />} />
        </Routes>
        <Footer />
      </BrowserRouter>
    </div>
  );
}

Route order doesn't matter in react-router-dom@6 as routes use a route path ranking system now to match the most appropriate path. react-router-dom@6中的路由顺序无关紧要,因为路由现在使用路由路径排名系统来匹配最合适的路径。 Routes are now always exactly matched as well, so there's no longer any exact prop.路线现在也总是完全匹配,因此不再有任何exact道具。

Route components that match paths still need a path prop.匹配路径的Route组件仍然需要一个path道具。 Specify a wildcard "*" path to match anything any of the more specific paths don't.指定通配符"*"路径以匹配任何更具体的路径不匹配的任何内容。

<Route path="*" element={<PageNotFound />} />

See How dow I add a No Match (404) route in react-router v6请参阅如何在 react-router v6 中添加不匹配 (404) 路由

// use it in this way it will work 

function App() {
  return (
    <div className="app">
      <BrowserRouter>
        <Header></Header>

        <Routes>
          <Route   path='*' element={<PageNotFound />} />
          <Route path='/' exact element={<Home />} />
          <Route path='/movie/:imdbID' element={<MovieDetails />} />
         
        </Routes>
        <Footer />
      </BrowserRouter>
    </div>
  );
}

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

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