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

当前回答

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 Router v6相关的答案来处理动态路由。

我创建了一个名为redirect的通用组件:

export default function Redirect(params) {
  window.location.replace('<Destination URL>' + "/." params.destination);

  return (
    <div />

  )
}

然后我在路由器文件中调用它:

<Route path='/wheretogo' element={<Redirect destination="wheretogo"/>}/>

我不认为React路由器提供这种支持。文档中提到

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

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

补充一下Víctor Daniel的回答:链接的路径名实际上只有在链接前有“https://'”或“http://'”时才会把你带到外部链接。

您可以执行以下操作:

<Link to={{ pathname:
> "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
> }} target="_blank" />

或者如果你的URL没有'https://', ',我会这样做:

<Link to={{pathname:`https://${link}`}} target="_blank" />

否则它将位于当前基路径的前面,如Lorenzo Demattécommented。

你可以使用你的动态URL:

<Link to={{pathname:`${link}`}}>View</Link>

最简单的解决方案是使用渲染函数并更改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>