React-Router 外部链接 [英] React-Router External link
问题描述
由于我在 React 应用程序中使用 react-router 来处理我的路由,我很好奇是否有办法重定向到外部资源.
Since I'm using react-router to handle my routes in a react app, I'm curious if there is a way to redirect to an external resource.
说有人点击:
example.com/privacy-policy
我希望它重定向到:
example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
我发现在我的 index.html 加载中避免使用纯 JS 编写它的帮助完全为零,例如:
I'm finding exactly zero help in avoiding writing it in plain JS at my index.html loading with something like:
if ( window.location.path === "privacy-policy" ){
window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}
推荐答案
实际上我最终构建了自己的组件.<重定向>
它从 react-router
元素获取信息,所以我可以将它保存在我的路由中.如:
I actually ended up building my own Component. <Redirect>
It takes info from the react-router
element so I can keep it in my routes. Such as:
<Route
path="/privacy-policy"
component={ Redirect }
loc="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies"
/>
这是我的组件以防万一有人好奇:
Here is my component incase-anyone is curious:
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中没那么简单
EDIT -- NOTE:
This is with react-router: 3.0.5
, it is not so simple in 4.x
这篇关于React-Router 外部链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!