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

当前回答

我最终创建了自己的组件,<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 v6中,组件不可用。相反,现在它支持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;

它不需要请求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路由器提供这种支持。文档中提到

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

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

我很幸运:

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

为了扩展Alan的回答,您可以创建一个<Route/>,它将所有包含“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
}}/>