由于我在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"
}
补充一下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。
最简单的解决方案是使用渲染函数并更改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>