反应路由器外部 link
React-Router External link
因为我在 React 应用程序中使用 react-router 来处理我的路由,所以我很好奇是否有一种方法可以重定向到外部资源。
假设有人点击:
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"
}
我认为 React-Router 不提供这种支持。 documentation 提及
A < Redirect > sets up a redirect to another route in your application to maintain old URLs.
您可以尝试使用 React-Redirect 之类的东西来代替
如果你正在使用服务器端渲染,你可以使用StaticRouter
。使用您的 context
作为 props
,然后在您的应用中添加 <Redirect path="/somewhere" />
组件。这个想法是每次 react-router 匹配一个重定向组件时,它都会在你传递给静态路由器的上下文中添加一些东西,让你知道你的路径匹配一个重定向组件。现在您知道您点击了重定向,您只需要检查这是否是您正在寻找的重定向。然后只需通过服务器重定向。 ctx.redirect('https://example/com')
。
实际上我最终构建了自己的组件。 <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
就没那么简单了
这是使用 React Router 重定向到外部的单行代码 link:
<Route path='/privacy-policy' component={() => {
window.location.href = 'https://example.com/1234';
return null;
}}/>
它使用 React 纯组件概念将组件的代码缩减为单个函数,而不是渲染任何内容,而是将浏览器重定向到外部 URL。
适用于 React Router 3 和 4。
不需要使用来自 react-router 的 <Link />
组件。
如果你想转到外部 link 使用锚标记。
<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>
适用于 V3,尽管它可能适用于 V4。离开埃里克的回答,我需要做更多的事情,比如处理 '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 一起使用会出现错误,因为该函数必须 return 一个反应元素,而不是 void
。所以我使用 Route render 方法(并使用 React router v4)这样做了:
redirectToHomePage = (): null => {
window.location.reload();
return null;
};
<Route exact path={'/'} render={this.redirectToHomePage} />
您也可以使用 window.location.assign()
、window.location.replace()
等
不需要请求react router。此操作可以本机完成,由浏览器提供。
只需使用window.location
使用 React Hooks
const RedirectPage = () => {
React.useEffect(() => {
window.location.replace('https://www.google.com')
}, [])
}
使用 React Class 组件
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 兼容。
它使用的是打字稿,但转换为本机应该相当简单 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 组件,您可以做到这一点。在 "to" 属性中你可以指定 3 种类型的数据:
- 字符串:Link 位置的字符串表示,通过连接位置的路径名、搜索和哈希属性创建。
- an object:可以具有以下任何属性的 object:
- pathname:表示路径的字符串link到.
- search: 查询参数的字符串表示。
- hash:要放入 URL 的散列,例如#a-hash.
- state: 状态持久化到位置。
- 一个函数:一个函数,当前位置作为参数传递给该函数并且应该 return 位置表示为字符串或 object
对于您的示例(外部 link):
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、类名等。
您现在可以 link 使用 React Link 访问外部站点,方法是使用 pathname
键向 to
提供 object:
<Link to={ { pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies' } } >
如果发现回调中需要用JS生成link,可以使用window.location.replace()
或window.location.assign()
。
在使用 window.location.replace()
时,正如其他好的答案所建议的那样,请尝试使用 window.location.assign()
。
window.location.replace()
将在不保留当前页面的情况下替换位置历史记录。
window.location.assign()
将过渡到指定的 url,但会在浏览器历史记录中保存上一页,从而允许正常的 back-button 功能。
https://developer.mozilla.org/en-US/docs/Web/API/Location/replace
https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
此外,如果您正在使用其他答案中提到的 window.location = url
方法,我强烈建议切换到 window.location.href = url
。
关于它有一个激烈的争论,许多用户似乎坚决希望将较新的 object
类型 window.location
恢复为 string
的原始实现,仅仅是因为他们可以(并且他们严重攻击任何人谁另有说法),但理论上您可以中断访问 window.location
object.
的其他库功能
看看这个会议。它是可怕的。
Javascript: Setting location.href versus location
我遇到了同样的问题。在 React js 中使用 http://
或 https://
解决了它。
赞为:
<a target="_blank" href="http://www.example.com/" title="example">See detail</a>
我遇到了同样的问题。我希望我的投资组合重定向到社交媒体句柄。早些时候我使用 {Link} from "react-router-dom".
重定向到这里的子目录,
Link 可用于在网站内路由网页。如果我们想重定向到外部 link 那么我们应该使用锚标记。像这样,
最简单的解决方案是使用 render function 并更改 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>
我自己(在我的网络应用程序中)解决了这个问题,方法是添加锚标记而不使用 React 路由器中的任何内容,只是一个带有 link 的普通锚标记,如图所示 screenshot of using anchor tag in a react.js app without using react router
基本上,您不会将用户路由到应用内的另一个页面,因此您不得使用内部路由器,而应使用普通锚点。
虽然这是非反应本机解决方案,但您可以尝试。
您可以为您的动态使用url
<Link to={{pathname:`${link}`}}>View</Link>
我认为最好的解决方案是只使用普通的旧 <a>
标签。其他一切似乎都令人费解。 React router 是为单页应用程序中的导航而设计的,因此将它用于其他任何事情都没有多大意义。为已经内置在 <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 应用程序中使用 react-router 来处理我的路由,所以我很好奇是否有一种方法可以重定向到外部资源。
假设有人点击:
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"
}
我认为 React-Router 不提供这种支持。 documentation 提及
A < Redirect > sets up a redirect to another route in your application to maintain old URLs.
您可以尝试使用 React-Redirect 之类的东西来代替
如果你正在使用服务器端渲染,你可以使用StaticRouter
。使用您的 context
作为 props
,然后在您的应用中添加 <Redirect path="/somewhere" />
组件。这个想法是每次 react-router 匹配一个重定向组件时,它都会在你传递给静态路由器的上下文中添加一些东西,让你知道你的路径匹配一个重定向组件。现在您知道您点击了重定向,您只需要检查这是否是您正在寻找的重定向。然后只需通过服务器重定向。 ctx.redirect('https://example/com')
。
实际上我最终构建了自己的组件。 <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
这是使用 React Router 重定向到外部的单行代码 link:
<Route path='/privacy-policy' component={() => {
window.location.href = 'https://example.com/1234';
return null;
}}/>
它使用 React 纯组件概念将组件的代码缩减为单个函数,而不是渲染任何内容,而是将浏览器重定向到外部 URL。
适用于 React Router 3 和 4。
不需要使用来自 react-router 的 <Link />
组件。
如果你想转到外部 link 使用锚标记。
<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>
适用于 V3,尽管它可能适用于 V4。离开埃里克的回答,我需要做更多的事情,比如处理 '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 一起使用会出现错误,因为该函数必须 return 一个反应元素,而不是 void
。所以我使用 Route render 方法(并使用 React router v4)这样做了:
redirectToHomePage = (): null => {
window.location.reload();
return null;
};
<Route exact path={'/'} render={this.redirectToHomePage} />
您也可以使用 window.location.assign()
、window.location.replace()
等
不需要请求react router。此操作可以本机完成,由浏览器提供。
只需使用window.location
使用 React Hooks
const RedirectPage = () => {
React.useEffect(() => {
window.location.replace('https://www.google.com')
}, [])
}
使用 React Class 组件
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 兼容。
它使用的是打字稿,但转换为本机应该相当简单 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 组件,您可以做到这一点。在 "to" 属性中你可以指定 3 种类型的数据:
- 字符串:Link 位置的字符串表示,通过连接位置的路径名、搜索和哈希属性创建。
- an object:可以具有以下任何属性的 object:
- pathname:表示路径的字符串link到.
- search: 查询参数的字符串表示。
- hash:要放入 URL 的散列,例如#a-hash.
- state: 状态持久化到位置。
- 一个函数:一个函数,当前位置作为参数传递给该函数并且应该 return 位置表示为字符串或 object
对于您的示例(外部 link):
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、类名等。
您现在可以 link 使用 React Link 访问外部站点,方法是使用 pathname
键向 to
提供 object:
<Link to={ { pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies' } } >
如果发现回调中需要用JS生成link,可以使用window.location.replace()
或window.location.assign()
。
在使用 window.location.replace()
时,正如其他好的答案所建议的那样,请尝试使用 window.location.assign()
。
window.location.replace()
将在不保留当前页面的情况下替换位置历史记录。
window.location.assign()
将过渡到指定的 url,但会在浏览器历史记录中保存上一页,从而允许正常的 back-button 功能。
https://developer.mozilla.org/en-US/docs/Web/API/Location/replace https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
此外,如果您正在使用其他答案中提到的 window.location = url
方法,我强烈建议切换到 window.location.href = url
。
关于它有一个激烈的争论,许多用户似乎坚决希望将较新的 object
类型 window.location
恢复为 string
的原始实现,仅仅是因为他们可以(并且他们严重攻击任何人谁另有说法),但理论上您可以中断访问 window.location
object.
看看这个会议。它是可怕的。 Javascript: Setting location.href versus location
我遇到了同样的问题。在 React js 中使用 http://
或 https://
解决了它。
赞为:
<a target="_blank" href="http://www.example.com/" title="example">See detail</a>
我遇到了同样的问题。我希望我的投资组合重定向到社交媒体句柄。早些时候我使用 {Link} from "react-router-dom".
重定向到这里的子目录,
Link 可用于在网站内路由网页。如果我们想重定向到外部 link 那么我们应该使用锚标记。像这样,
最简单的解决方案是使用 render function 并更改 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>
我自己(在我的网络应用程序中)解决了这个问题,方法是添加锚标记而不使用 React 路由器中的任何内容,只是一个带有 link 的普通锚标记,如图所示 screenshot of using anchor tag in a react.js app without using react router
基本上,您不会将用户路由到应用内的另一个页面,因此您不得使用内部路由器,而应使用普通锚点。
虽然这是非反应本机解决方案,但您可以尝试。
您可以为您的动态使用url
<Link to={{pathname:`${link}`}}>View</Link>
我认为最好的解决方案是只使用普通的旧 <a>
标签。其他一切似乎都令人费解。 React router 是为单页应用程序中的导航而设计的,因此将它用于其他任何事情都没有多大意义。为已经内置在 <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>