Javascript React-Router 外部链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42914666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React-Router External link
提问by Eric Hodonsky
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.
由于我在 React 应用程序中使用 react-router 来处理我的路由,我很好奇是否有办法重定向到外部资源。
Say someone hits:
说有人打:
example.com/privacy-policy
example.com/privacy-policy
I would like it to redirect to:
我希望它重定向到:
example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
I'm finding exactly zero help in avoiding writing it in plain JS at my index.html loading with something like:
我发现在我的 index.html 加载中避免在纯 JS 中编写它的帮助为零,例如:
if ( window.location.path === "privacy-policy" ){
window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}
采纳答案by Eric Hodonsky
I actually ended up building my own Component. <Redirect>It takes info from the react-routerelement so I can keep it in my routes. Such as:
我实际上最终构建了自己的组件。<Redirect>它从react-router元素中获取信息,因此我可以将其保留在我的路线中。如:
<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;
EDIT -- NOTE:
This is with react-router: 3.0.5, it is not so simple in 4.x
编辑 - 注意:这是与react-router: 3.0.5,它在 4.x 中并不那么简单
回答by Evgeny Lukianchikov
Here's a one-liner for using React Router to redirect to an external link:
这是使用 React Router 重定向到外部链接的单行代码:
<Route path='/privacy-policy' component={() => {
window.location.href = 'https://example.com/1234';
return null;
}}/>
It uses React pure component concept to reduce the component's code to a single function that, instead of rendering anything, redirects browser to an external URL.
它使用 React 纯组件概念将组件的代码简化为单个函数,而不是渲染任何内容,而是将浏览器重定向到外部 URL。
Works both on React Router 3 and 4.
适用于 React Router 3 和 4。
回答by Diego Laciar
There is no need to use <Link />component from react-router.
无需使用<Link />react-router 中的组件。
If you want to go to external link use an anchor tag.
如果您想转到外部链接,请使用锚标记。
<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>
回答by Alan
It doesn't need to request react router. This action can be done natively and it is provided by the browser.
它不需要请求反应路由器。此操作可以在本地完成,并且由浏览器提供。
just use window.location
只是使用 window.location
class RedirectPage extends React.Component {
componentDidMount(){
window.location.replace('http://www.google.com')
}
}
回答by Jens Bodal
Using some of the info here, I came up with the following component which you can use within your route declarations. It's compatible with React Router v4.
使用这里的一些信息,我想出了以下组件,您可以在路由声明中使用它。它与 React Router v4 兼容。
It's using typescript, but should be fairly straight-forward to convert to native javascript:
它使用打字稿,但转换为原生 javascript 应该相当简单:
interface Props {
exact?: boolean;
link: string;
path: string;
sensitive?: boolean;
strict?: boolean;
}
const ExternalRedirect: React.FC<Props> = (props: Props) => {
const { link, ...routeProps } = props;
return (
<Route
{...routeProps}
render={() => {
window.location.replace(props.link);
return null;
}}
/>
);
};
And use with:
并与:
<ExternalRedirect
exact={true}
path={'/privacy-policy'}
link={'https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}
/>
回答by Alex Billson
I had luck with this:
我很幸运:
<Route
path="/example"
component={() => {
global.window && (global.window.location.href = 'https://example.com');
return null;
}}
/>
回答by Sam Mckay
To expand on Alan's answer, you can create a <Route/>that redirects all <Link/>'s with "to" attributes containing 'http:' or 'https:' to the correct external resource.
要扩展 Alan 的答案,您可以创建一个<Route/>将所有<Link/>带有包含“http:”或“https:”的“to”属性的 's重定向到正确的外部资源。
Below is a working example of this which can be placed directly into your <Router>.
下面是一个工作示例,它可以直接放入您的<Router>.
<Route path={['/http:', '/https:']} component={props => {
window.location.replace(props.location.pathname.substr(1)) // substr(1) removes the preceding '/'
return null
}}/>
回答by ytibrewala
I don't think React-Router provides this support. The documentationmentions
我不认为 React-Router 提供这种支持。该文件提到
A < Redirect > sets up a redirect to another route in your applicationto maintain old URLs.
< Redirect > 设置重定向到应用程序中的另一个路由以维护旧 URL。
You could try using something like React-Redirectinstead
你可以尝试使用类似阵营重定向代替
回答by MattC
FOR V3, although it may work for V4. Going off of Eric's answer, I needed to do a little more, like handle local development where 'http' is not present on the url. I'm also redirecting to another application on the same server.
对于 V3,虽然它可能适用于 V4。离开埃里克的回答,我需要做更多的事情,比如处理 url 上不存在“http”的本地开发。我还重定向到同一服务器上的另一个应用程序。
Added to router file:
添加到路由器文件:
import RedirectOnServer from './components/RedirectOnServer';
<Route path="/somelocalpath"
component={RedirectOnServer}
target="/someexternaltargetstring like cnn.com"
/>
And the Component:
和组件:
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;
回答by Víctor Daniel
With Link component of react-router you can do that. In the "to" prop you can specify 3 types of data:
使用 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
- a string:链接位置的字符串表示形式,通过连接位置的路径名、搜索和哈希属性创建。
- 对象:可以具有以下任何属性的对象:
- pathname: 表示要链接到的路径的字符串。
- search:查询参数的字符串表示形式。
- hash: 放在 URL 中的哈希,例如 #a-hash。
- state: 坚持到该位置的状态。
- 一个函数:一个函数,当前位置作为参数传递给它,它应该以字符串或对象的形式返回位置表示
For your example (external link):
对于您的示例(外部链接):
https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
You can do the following:
您可以执行以下操作:
<Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />
You can also pass props you'd like to be on the such as a title, id, className, etc.
您还可以传递您想要的道具,例如标题、id、className 等。

