小编典典

React-Router外部链接

javascript

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

阅读 958

收藏
2020-05-01

共1个答案

小编典典

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

2020-05-01