由于我在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-router的Link组件就可以做到。在“to”道具中,您可以指定3种类型的数据:
a string: A string representation of the Link location, created by concatenating the location’s pathname, search, and hash properties.
an object: An object that can have any of the following properties:
pathname: A string representing the path to link to.
search: A string representation of query parameters.
hash: A hash to put in the URL, e.g. #a-hash.
state: State to persist to the location.
a function: A function to which current location is passed as an argument and which should return location representation as a string or as an object
对于你的例子(外部链接):
https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
您可以执行以下操作:
<Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />
您还可以传递您想要的道具,如标题,id, className等。
我最终创建了自己的组件,<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中没有这么简单
最简单的解决方案是使用渲染函数并更改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>