由于我在React应用程序中使用React路由器来处理我的路由,我很好奇是否有一种方法可以重定向到外部资源。

比如有人打人:

example.com/privacy-policy

我希望它重定向到:

example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies

我发现在我的index.html加载中,避免用纯JavaScript编写它完全没有任何帮助:

if (window.location.path === "privacy-policy"){
  window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}

当前回答

如果你使用服务器端渲染,你可以使用StaticRouter。用你的上下文作为道具,然后在你的应用程序中添加<重定向路径="/somewhere" />组件。这个想法是每次React路由器匹配一个重定向组件时,它会添加一些东西到你传递到静态路由器的上下文中,让你知道你的路径匹配一个重定向组件。

现在你知道你点击了一个重定向,你只需要检查这是否是你正在寻找的重定向。然后通过服务器重定向。ctx.redirect(“https://example/com”)。

其他回答

我自己解决了这个问题(在我的web应用程序中),通过添加一个锚标记,而不是使用React路由器的任何东西,只是一个普通的锚标记和一个链接,正如你可以在图片截图中看到的,在一个React应用程序中使用锚标记而不使用React路由器

基本上,你不会将你的用户路由到你的应用程序中的另一个页面,所以你不能使用内部路由器,而是使用一个正常的锚。

虽然这是一个非反应本机解决方案,但您可以尝试。

你现在可以使用React link通过提供一个对象的路径名键链接到外部站点:

<链接到={{pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}} > . <链接到={{pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies

如果您发现需要使用JavaScript在回调中生成链接,则可以使用window.location.replace()或window.location.assign()。

过度使用window.location.replace(),就像其他好的答案建议的那样,尝试使用window.location.assign()。

Window.location.replace()将替换位置历史而不保留当前页面。

window.location.assign()将转换到指定的URL,但将保存浏览器历史记录中的前一页,允许适当的后退按钮功能。

location.replace ()

location.assign ()

此外,如果您使用窗口。location = url方法,如在其他答案中提到的,我强烈建议切换到window.location.href = url。

关于它有一个很大的争论,许多用户似乎坚定地希望恢复较新的对象类型窗口。将其原始实现定位为字符串仅仅是因为它们可以(并且它们会攻击任何不这样说的人),但是理论上您可以中断访问该窗口的其他库功能。位置的对象。

看看这段对话。这是可怕的。 设置位置。Href与位置

用react-router的Link组件就可以做到。在“to”道具中,您可以指定3种类型的数据:

a string: A string representation of the Link location, created by concatenating the location’s pathname, search, and hash properties. an object: An object that can have any of the following properties: pathname: A string representing the path to link to. search: A string representation of query parameters. hash: A hash to put in the URL, e.g. #a-hash. state: State to persist to the location. a function: A function to which current location is passed as an argument and which should return location representation as a string or as an object

对于你的例子(外部链接):

https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies

您可以执行以下操作:

<Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />

您还可以传递您想要的道具,如标题,id, className等。

在React Route V6中,渲染道具被移除。它应该是一个重定向组件。

重定向网址:

const RedirectUrl = ({ url }) => {
  useEffect(() => {
    window.location.href = url;
  }, [url]);

  return <h5>Redirecting...</h5>;
};

路线:

<Routes>
   <Route path="/redirect" element={<RedirectUrl url="https://google.com" />} />
</Routes>

为了扩展Alan的回答,您可以创建一个<Route/>,它将所有包含“http:”或“https:”属性的<Link/>重定向到正确的外部资源。

下面是一个可以直接放在<Router>中的工作示例。

<Route path={['/http:', '/https:']} component={props => {
  window.location.replace(props.location.pathname.substr(1)) // substr(1) removes the preceding '/'
  return null
}}/>