由于我在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"
}
我最终创建了自己的组件,<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中没有这么简单
对于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;