由于我在React应用程序中使用React路由器来处理我的路由,我很好奇是否有一种方法可以重定向到外部资源。

比如有人打人:

example.com/privacy-policy

我希望它重定向到:

example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies

我发现在我的index.html加载中,避免用纯JavaScript编写它完全没有任何帮助:

if (window.location.path === "privacy-policy"){
  window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}

当前回答

我提供了一个与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"/>}/>

其他回答

我最终创建了自己的组件,<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路由器。这个操作可以在本地完成,由浏览器提供。

只需使用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和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 Router重定向到外部链接的一行代码:

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

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

它在React Router 3和4上都可以工作。

我很幸运:

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