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

当前回答

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

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

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

其他回答

它不需要请求React路由器。这个操作可以在本地完成,由浏览器提供。

只需使用window.location。

React挂钩

const RedirectPage = () => {
  React.useEffect(() => {
    window.location.replace('https://www.google.com')
  }, [])
}

使用React类组件

class RedirectPage extends React.Component {
  componentDidMount(){
    window.location.replace('https://www.google.com')
  }
}

另外,如果你想在一个新标签中打开它:

window.open('https://www.google.com', '_blank');

补充一下Víctor Daniel的回答:链接的路径名实际上只有在链接前有“https://'”或“http://'”时才会把你带到外部链接。

您可以执行以下操作:

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

或者如果你的URL没有'https://', ',我会这样做:

<Link to={{pathname:`https://${link}`}} target="_blank" />

否则它将位于当前基路径的前面,如Lorenzo Demattécommented。

对于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;

为了扩展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
}}/>

我很幸运:

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