由于我在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路由器提供这种支持。文档中提到

重定向>设置重定向到应用程序中的另一个路由,以维护旧的url。

你可以尝试使用类似React-Redirect的东西。

我提供了一个与React Router v6相关的答案来处理动态路由。

我创建了一个名为redirect的通用组件:

export default function Redirect(params) {
  window.location.replace('<Destination URL>' + "/." params.destination);

  return (
    <div />

  )
}

然后我在路由器文件中调用它:

<Route path='/wheretogo' element={<Redirect destination="wheretogo"/>}/>

对于V3,虽然对V4也适用。离开Eric的回答,我需要做更多的事情,比如处理本地开发,其中'http'不存在于URL上。我还重定向到同一服务器上的另一个应用程序。

添加到路由器文件:

import RedirectOnServer from './components/RedirectOnServer';

<Route path="/somelocalpath"
       component={RedirectOnServer}
       target="/someexternaltargetstring like cnn.com"
/>

和组件:

import React, { Component } from "react";

export class RedirectOnServer extends Component {

  constructor(props) {
    super();
    // If the prefix is http or https, we add nothing
    let prefix = window.location.host.startsWith("http") ? "" : "http://";
    // Using host here, as I'm redirecting to another location on the same host
    this.target = prefix + window.location.host + props.route.target;
  }
  componentDidMount() {
    window.location.replace(this.target);
  }
  render(){
    return (
      <div>
        <br />
        <span>Redirecting to {this.target}</span>
      </div>
    );
  }
}

export default RedirectOnServer;

我认为最好的解决方案是使用普通的<a>标记。其他一切似乎都令人费解。React路由器是为单页应用程序中的导航而设计的,因此将它用于其他任何事情都没有多大意义。为已经内置在<a>标签中的东西制作整个组件似乎…傻吗?