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

其他回答

你现在可以使用React link通过提供一个对象的路径名键链接到外部站点:

<链接到={{pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}} > . <链接到={{pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies

如果您发现需要使用JavaScript在回调中生成链接,则可以使用window.location.replace()或window.location.assign()。

过度使用window.location.replace(),就像其他好的答案建议的那样,尝试使用window.location.assign()。

Window.location.replace()将替换位置历史而不保留当前页面。

window.location.assign()将转换到指定的URL,但将保存浏览器历史记录中的前一页,允许适当的后退按钮功能。

location.replace ()

location.assign ()

此外,如果您使用窗口。location = url方法,如在其他答案中提到的,我强烈建议切换到window.location.href = url。

关于它有一个很大的争论,许多用户似乎坚定地希望恢复较新的对象类型窗口。将其原始实现定位为字符串仅仅是因为它们可以(并且它们会攻击任何不这样说的人),但是理论上您可以中断访问该窗口的其他库功能。位置的对象。

看看这段对话。这是可怕的。 设置位置。Href与位置

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

我很幸运:

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

在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>

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