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

当前回答

我很幸运:

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

其他回答

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

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

你现在可以使用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与位置

使用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路由器提供这种支持。文档中提到

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

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

我能够在react-router-dom中使用以下方法实现重定向

<Route exact path="/" component={() => <Redirect to={{ pathname: '/YourRoute' }} />} />

对于我的案例,我正在寻找一种方法,每当用户访问根URL http://myapp.com时,将他们重定向到应用程序http://myapp.com/newplace中的其他地方。因此,上述方法有所帮助。