简体   繁体   English

react-router-dom v 6.0.0 中重定向的替代方法是什么?

[英]What is the alternative for Redirect in react-router-dom v 6.0.0?

New version of react-router-dom (v6.0.0) doesn't identify "Redirect".新版本的 react-router-dom (v6.0.0) 不识别“重定向”。 What is the alternative for it?它的替代方案是什么?

Redirect alone is done via the Navigate component with the replace prop specified.单独的重定向是通过Navigate组件完成的,并指定了replace属性。

<Navigate replace to="/" />

If you want to replicate redirecting from a path then you need to combine with a Route .如果要从路径复制重定向,则需要与Route结合使用。

<Route path="/somePath" element={<Navigate replace to="/" />} />

If you aren't server rendering your app you can still redirect on the initial render in the client like this:如果您不是服务器渲染您的应用程序,您仍然可以在客户端的初始渲染上重定向,如下所示:

import { Routes, Route, Navigate } from "react-router-dom";

    function App() {
      return (
        <Routes>
          <Route path="/home" element={<Home />} />
          <Route path="/" element={<Navigate replace to="/home" />} />
        </Routes>
      );
    }

In the above example, when someone visits / , they will automatically be redirected to /home , same as before.在上面的例子中,当有人访问/时,他们会自动被重定向到/home ,和之前一样。

Please note however that this won't work when server rendering because the navigation happens in a React.useEffect() .但是请注意,这在服务器渲染时不起作用,因为导航发生在React.useEffect()中。

Have a look at Redirects in React Router v6 for some deeper details.查看React Router v6 中的 Redirects 以获得更深入的细节。

以下是 react-router-dom 团队在 v6 中删除该 API 时就重定向问题所说的话: https:\/\/github.com\/remix-run\/react-router\/blob\/main\/docs\/upgrading\/reach。 md#redirect-redirectto-isredirect<\/a>

"

Redirecting in react-router-dom v6 is done with the <Navigate> Component with replace props. react-router-dom v6 中的重定向是使用带有replace道具的<Navigate>组件完成的。

Step 1:步骤1:

import { Navigate } from 'react-router-dom';

Step 2:第2步:

<Routes>
    <Route path='/' element={<Navigate replace to='/search' />} />
</Routes>

In v6.2.* Just add a Route with path to *v6.2.*中,只需添加一个路径为*

<Routes>
  <Route path="/" element={<App />}>
    <Route path="expenses" element={<Expenses />} />
   
    <Route
      path="*"
      element={
        <main style={{ padding: "1rem" }}>
          <p>There's nothing here!</p>
        </main>
      }
    />
  </Route>
</Routes>

Official Doc 官方文件

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

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