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

当前回答

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

其他回答

在React Route V6中,渲染道具被移除。它应该是一个重定向组件。

重定向网址:

const RedirectUrl = ({ url }) => {
  useEffect(() => {
    window.location.href = url;
  }, [url]);

  return <h5>Redirecting...</h5>;
};

路线:

<Routes>
   <Route path="/redirect" element={<RedirectUrl url="https://google.com" />} />
</Routes>

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

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

利用这里的一些信息,我提出了以下组件,您可以在路由声明中使用它。它与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'}
/>

最简单的解决方案是使用渲染函数并更改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>