React-Router-Link vs Redirect vs History

似乎有一些关于使用什么的混乱:

  • <Link to='/some/path'>
  • <Redirect to='/some/path'/>
  • history.push('/some/path')

我已经使用 React/Router 有一段时间了,不同的帖子/回答在什么时候使用这些内容上有不同的表述,有时候它们与别人说的不一致。所以我想我需要澄清一下。

根据我对 Link和这个 文件的了解:

提供关于应用程序的声明性的、可访问的导航。

根据我对 Redirect和这个 文件的了解:

将导航到新位置。新位置将覆盖历史堆栈中的当前位置,就像服务器端重定向(HTTP 3xx)所做的那样。

似乎我读过的所有文章几乎每个人都使用 Redirect来导航那里的应用程序,没有人曾经推荐使用 Link喜欢在这个 邮寄

现在 history可以做与 LinkRedirect相同的事情,除了我有一个历史堆栈跟踪。

问题1: 什么时候我想使用 LinkRedirect,相对于其他用例,这个用例是什么?

问题2: 既然 history可以通过添加历史堆栈来将用户路由到应用程序中的另一个位置,我是否应该在路由时总是使用历史对象?

问题3: 如果我想路由应用程序的 在外面,最好的方法是什么?锚标签,Window.location.href,重定向,链接,都不是吗?

43063 次浏览

First off, I would really recommend reading through this site:
https://reacttraining.com/react-router/web/api/BrowserRouter

React Router's BrowserRouter maintains the history stack for you, which means that you rarely need to modify it manually.

But to answer your questions:
Answer 1: You'll want to use Link or NavLink in almost all use cases. Redirect comes in handy in specific situations though, an example is when a 404 page is rendered when the user tries to access an undefined route. The Redirect will redirect the user from the 404 route to a new route of your choosing, and then replace the last entry in the history stack with the redirected route.

This means that the user will not be able to hit their browser's back button, and return to the 404 route.

Link NavLink and Redirect all use the router's history api under the hood, using these components instead of history manually means that you are safe to any changes to the history api in the future. Using these components future-proofs your code.

Answer 2: BrowserRouter Maintains the history stack for you, generally my opinion is that you want to stay away from manually updating it where you can.

Answer 3: Here are a few examples for external react links:

<Route path='/external' component={() => window.location = 'https://external.com/path'}/>

<a href='https://external.com/path' target='_blank' rel='noopener noreferrer'>Regular Anchor tags work great</a>

target='_blank' will open the link in a new tab, but please make sure to include rel='noopener noreferrer' to prevent against vulnerabilities