发送 404 状态并重定向到 react-router 中的 404 组件

Send both 404 status and redirect to 404 component in react-router

我有一个 react-router 3.0.0 设置,其中有一个 NotFound 组件,我将其显示为后备:

<Route component={NotFound} path="*"/>

但是这个 returns 重定向和 google 爬虫抱怨软 404。我可以同时重定向到我的 NotFound 组件并发送 404,类似于 Github 所做的吗?我从这里尝试了以下建议:How to let react router respond with 404 status code?

<Route component={NotFound} path="*" status={404}/>

但这只是给我一个 404 而没有显示组件。

以上如何实现?

React Router v6

现场演示:Redirect Default or 404 Routes with React Router

示例代码:

<Router>
  <Routes>
    <Route path="users" element={<Users />} />
    <Route path="posts" element={<Posts />} />
  </Routes>
</Router>

要重定向并导航到我们选择的路线之一,我们可以使用 React Router 中的组件。现在我们可以在路由配置下方声明空路由的情况,如下所示:

<Router>
  <Routes>
    <Route path="users" element={<Users />} />
    <Route path="posts" element={<Posts />} />
    <Route path="" element={<Navigate to="/users" />} />
  </Routes>
</Router>