因为我使用react路由器来处理我的路由,所以我很好奇是否有一种方法可以重定向到外部资源。
说有人打:
example.com/privacy-policy
我希望它能重定向到:
example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
在我的index.html加载时,我发现避免用普通的JS编写它完全没有任何帮助,比如:
if ( window.location.path === "privacy-policy" ){
window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}发布于 2017-03-23 22:38:55
实际上,我最终建立了自己的组件。<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中并不那么简单
发布于 2017-06-15 09:30:06
下面是一个使用React路由器重定向到外部链接的一行:
<Route path='/privacy-policy' component={() => {
window.location.href = 'https://example.com/1234';
return null;
}}/>它使用function纯组件概念将组件的代码简化为一个函数,而不是呈现任何内容,而是将浏览器重定向到外部URL。
工作在反应路由器3和4。
发布于 2020-05-26 18:25:53
有了react路由器的Link组件,您就可以做到这一点。在"to“支柱中,您可以指定3种类型的数据:
对于您的示例(外部链接):
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等。
https://stackoverflow.com/questions/42914666
复制相似问题