React-Router外部链路

由于我使用react-router在一个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"
}
491539 次浏览

我不认为React-Router提供这种支持。文档提到

& lt;重定向>设置了一个重定向到您的应用程序中的另一个路由,以维护旧的url。

你可以尝试使用类似React-Redirect的东西

如果你正在使用服务器端渲染,你可以使用StaticRouter。用你的context作为props,然后在你的应用程序中添加<Redirect path="/somewhere" />组件。这个想法是每次react-router匹配一个重定向组件时,它会在你传递给静态路由器的上下文中添加一些东西,让你知道你的路径匹配一个重定向组件。现在你知道你击中了一个重定向,你只需要检查这是否是你正在寻找的重定向。然后通过服务器重定向。ctx.redirect('https://example/com')

我实际上最终建立了我自己的组件。<Redirect> 它从react-router元素中获取信息,因此我可以将它保留在我的路由中。如:< / p >
<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

中不是那么简单

下面是使用React Router重定向到外部链接的一行代码:

<Route path='/privacy-policy' component={() => {
window.location.href = 'https://example.com/1234';
return null;
}}/>

它使用React纯组件概念,将组件代码减少为一个函数,而不是渲染任何东西,将浏览器重定向到外部URL。

适用于React Router 3和4。

没有必要使用react-router中的<Link />组件。

如果你想去外部链接使用锚标签。

<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>

FOR 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;

使用React和Typescript,你会得到一个错误,因为函数必须返回一个React元素,而不是void。所以我这样做,使用Route渲染方法(并使用React路由器v4):

redirectToHomePage = (): null => {
window.location.reload();
return null;
};
<Route exact path={'/'} render={this.redirectToHomePage} />

在哪里你也可以使用window.location.assign()window.location.replace()

它不需要请求react路由器。这个操作可以在本地完成,由浏览器提供。

只要使用window.location即可

React挂钩

const RedirectPage = () => {
React.useEffect(() => {
window.location.replace('https://www.google.com')
}, [])
}

使用React类组件

class RedirectPage extends React.Component {
componentDidMount(){
window.location.replace('https://www.google.com')
}
}

另外,如果你想在一个新标签中打开它:

window.open('https://www.google.com', '_blank');

我能够在react-router-dom中使用以下方法实现重定向

<Route exact path="/" component={() => <Redirect to=\{\{ pathname: '/YourRoute' }} />} />

对于我的案例,我正在寻找一种方法,每当用户访问根URL http://myapp.com时,将用户重定向到应用程序http://myapp.com/newplace中的其他地方。因此,上述方法有所帮助。

使用这里的一些信息,我提出了以下组件,你可以在你的路由声明中使用。它与React Router v4兼容。

它使用的是typescript,但转换为原生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;
}}
/>
);
};

与…一起使用:

<ExternalRedirect
exact={true}
path={'/privacy-policy'}
link={'https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}
/>

为了扩展Alan的回答,你可以创建一个<Route/>,它将所有带有“To”属性的包含“http:”或“https:”的<Link/>重定向到正确的外部资源。

下面是一个可以直接放入<Router>的工作示例。

<Route path={['/http:', '/https:']} component={props => {
window.location.replace(props.location.pathname.substr(1)) // substr(1) removes the preceding '/'
return null
}}/>

我很幸运:

  <Route
path="/example"
component={() => {
global.window && (global.window.location.href = 'https://example.com');
return null;
}}
/>

用react-router的Link组件就可以做到。在""道具中,你可以指定3种类型的数据:

  • 一个字符串:链接位置的字符串表示,通过连接位置的路径名、搜索和散列属性创建。
  • 一个对象:可以具有以下任意属性的对象:
    • 路径名:表示要链接的路径的字符串。
    • 搜索:查询参数的字符串表示形式。
    • 哈希:要放入URL中的散列,例如# A -hash。
    • 状态:持久化到位置的状态。
    • 李< / ul > < / >
    • 一个函数:将当前位置作为参数传递给的函数,该函数应以字符串或对象的形式返回位置表示

    对于你的例子(外部链接):

    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等。

你现在可以使用React link通过pathname键向to提供一个对象来链接到外部站点:

<Link to={ { pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies' } } >

如果你发现你需要使用JS在回调中生成链接,你可以使用window.location.replace()window.location.assign()

过量使用window.location.replace(),正如其他好的答案所建议的那样,尝试使用window.location.assign()

window.location.replace()将替换位置历史而不保留当前页面。

window.location.assign()将转换到指定的url,但将保存浏览器历史记录中的上一页,允许适当的后退按钮功能。

https://developer.mozilla.org/en-US/docs/Web/API/Location/replace https://developer.mozilla.org/en-US/docs/Web/API/Location/assign < / p > 同样,如果你正在使用其他答案中提到的window.location = url方法,我强烈建议切换到window.location.href = url。 关于它有一个激烈的争论,许多用户似乎坚定地希望将更新的object类型window.location恢复到其原始的实现string,仅仅因为他们可以(并且他们极端地攻击任何不这样说的人),但理论上你可以中断其他库功能访问window.location对象

看看这个对话。这是可怕的。 设置位置。Href与位置 < / p >

我也面临着同样的问题。在react js中使用http://https://解决了它。

< p >像: <a target="_blank" href="http://www.example.com/" title="example">See detail</a> < / p >

我也遇到过同样的问题。我希望我的投资组合重定向到社交媒体处理。之前我使用了{Link} from "react-router-dom".,它重定向到这里的子目录,

enter image description here

链接可用于在网站内路由网页。如果我们想重定向到一个外部链接,那么我们应该使用一个锚标记。像这样,

enter image description here

最简单的解决方案是使用渲染函数并更改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>

我自己解决了这个问题(在我的web应用程序),通过添加一个锚标记,而不是使用React路由器的任何东西,只是一个普通的锚标记与链接,你可以在图片在react.js应用中使用锚标记而不使用react路由器的截图中看到

基本上,你不路由你的用户到你的应用程序内的另一个页面,所以你不能使用内部路由器,而是使用一个正常的锚。

虽然这是一个非反应本机解决方案,但您可以尝试。

可以用于动态url

<Link to=\{\{pathname:`${link}`}}>View</Link>


我认为最好的解决方案是只使用普通的<a>标签。其他一切似乎都令人费解。React路由器是为单页应用程序中的导航而设计的,因此将它用于其他任何事情都没有多大意义。为<a>标记中已经内置的内容创建整个组件似乎……傻吗?

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";


function App() {
return (
<Router>
<Route path="/" exact>
{window.location.replace("http://agrosys.in")}
</Route>
</Router>
);
}


export default App;

在React Route V6中,渲染道具被移除。应该是一个重定向组件。

RedirectUrl:

const RedirectUrl = ({ url }) => {
useEffect(() => {
window.location.href = url;
}, [url]);


return <h5>Redirecting...</h5>;
};

路线:

<Routes>
<Route path="/redirect" element={<RedirectUrl url="https://google.com" />} />
</Routes>

在React Router v6中,component不可用。相反,现在它支持element。制作一个组件重定向到外部站点,并按所示添加它。

import * as React from 'react';
import { Routes, Route } from "react-router-dom";


function App() {
return(
<Routes>
// Redirect
<Route path="/external-link" element={<External />} />
</Routes>
);
}


function External() {
window.location.href = 'https://google.com';
return null;
}


export default App;

在这里补充@víctor-daniel的回答:链接的pathname实际上只会在链接前有'https://' '或'http://'时将你带到外部链接

您可以执行以下操作:

<Link to=\{\{ pathname:
> "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
> }} target="_blank" />

或者如果你的url没有'https://' ',我会这样做:

<Link to=\{\{pathname:`https://${link}`}} target="_blank" />

否则,它将位于当前基路径的前面,如@lorenzo-dematté所评论的那样

提供一个与react-router v6相关的答案来处理动态路由。

我创建了一个名为redirect的通用组件:

export default function Redirect(params) {
window.location.replace('<Destination URL>' + "/." params.destination);


return (
<div />


)
}

然后我在路由器文件中调用它:

<Route path='/wheretogo' element={<Redirect destination="wheretogo"/>}/>