React-Router外部链接

JavaScript

番长卡卡西

2020-03-13

由于我正在使用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"
}

第1389篇《React-Router外部链接》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
斯丁村村GO 2020.03.13

使用带有Typescript的React会出错,因为该函数必须返回react元素,而不是void因此,我使用了Route渲染方法(以及使用React Router v4)来做到这一点:

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

您还可以在其他地方使用window.location.assign()window.location.replace()等等

猴子凯 2020.03.13

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

<重定向>设置到应用程序中另一个路由的重定向,以维护旧的URL。

你可以尝试使用类似阵营重定向代替

达蒙Gil 2020.03.13

无需使用<Link />react-router中的组件。

如果要转到外部链接,请使用锚标记。

<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>
逆天Green古一 2020.03.13

我实际上最终构建了自己的组件。<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中不是那么简单

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android