由于我在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"
}

当前回答

不需要使用React Router中的<Link />组件。

如果你想去外部链接使用锚标签。

<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>

其他回答

下面是使用React Router重定向到外部链接的一行代码:

<Route path='/privacy-policy' component={() => {
    window.location.href = 'https://example.com/1234';
    return null;
}}/>

它使用React纯组件概念,将组件代码减少为一个函数,而不是渲染任何东西,将浏览器重定向到外部URL。

它在React Router 3和4上都可以工作。

不需要使用React Router中的<Link />组件。

如果你想去外部链接使用锚标签。

<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>

在React Router v6中,组件不可用。相反,现在它支持element。制作一个组件重定向到外部站点,并按所示添加它。

import * as React from 'react';
import { Routes, Route } from "react-router-dom";

function App() {
  return(
    <Routes>
      // Redirect
      <Route path="/external-link" element={<External />} />
    </Routes>
  );
}

function External() {
  window.location.href = 'https://google.com';
  return null;
}

export default App;

我也遇到过同样的问题。我希望我的投资组合重定向到社交媒体处理。之前我使用了"react-router-dom"中的{Link}。重定向到这里的子目录,

链接可用于在网站内路由网页。如果我们想重定向到一个外部链接,那么我们应该使用一个锚标记。像这样,

最简单的解决方案是使用渲染函数并更改window.location。

<Route path="/goToGoogle"
       render={() => window.location = "https://www.google.com"} />

如果你想要一个小型的可重用组件,你可以像这样提取它:

const ExternalRedirect = ({ to, ...routeProps }) => {
   return <Route {...routeProps} render={() => window.location = to} />;
};

然后像这样使用它(例如在你的路由器开关中):

<Switch>
    ...
    <ExternalRedirect exact path="/goToGoogle" to="https://www.google.com" />
</Switch>