由于我在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”)。

其他回答

利用这里的一些信息,我提出了以下组件,您可以在路由声明中使用它。它与React Router v4兼容。

它使用的是TypeScript,但转换为原生JavaScript应该相当简单:

interface Props {
  exact?: boolean;
  link: string;
  path: string;
  sensitive?: boolean;
  strict?: boolean;
}

const ExternalRedirect: React.FC<Props> = (props: Props) => {
  const { link, ...routeProps } = props;

  return (
    <Route
      {...routeProps}
      render={() => {
        window.location.replace(props.link);
        return null;
      }}
    />
  );
};

与…一起使用:

<ExternalRedirect
  exact={true}
  path={'/privacy-policy'}
  link={'https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}
/>

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

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

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

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";

function App() {
  return (
    <Router>
      <Route path="/" exact>
        {window.location.replace("http://agrosys.in")}
      </Route>
    </Router>
  );
}

export default App;

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

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

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

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

我最终创建了自己的组件,<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中没有这么简单