由于我在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和TypeScript,你会得到一个错误,因为函数必须返回一个React元素,而不是void。所以我这样做,使用Route渲染方法(并使用React路由器v4):

redirectToHomePage = (): null => {
    window.location.reload();
    return null;
};

<Route exact path={'/'} render={this.redirectToHomePage} />

你也可以使用window.location.assign(), window.location.replace()等。

其他回答

我遇到了同样的问题,并在React中使用http://或https://解决了它。

像: <a target="_blank" href="http://www.example.com/" title="example">见detail</a>

我不认为React路由器提供这种支持。文档中提到

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

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

我最终创建了自己的组件,<Redirect>。 它从react-router元素中获取信息,所以我可以将它保留在我的路由中。如:

<Route
  path="/privacy-policy"
  component={ Redirect }
  loc="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies"
  />

下面是我的组件,以防有人好奇:

import React, { Component } from "react";

export class Redirect extends Component {
  constructor( props ){
    super();
    this.state = { ...props };
  }
  componentWillMount(){
    window.location = this.state.route.loc;
  }
  render(){
    return (<section>Redirecting...</section>);
  }
}

export default Redirect;

注意:这是react-router: 3.0.5,在4.x中没有这么简单

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

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

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

我很幸运:

<Route
    path="/example"
    component={() => {
        global.window && (global.window.location.href = 'https://example.com');
        return null;
    }}
/>