由于我在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路由器提供这种支持。文档中提到

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

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

用react-router的Link组件就可以做到。在“to”道具中,您可以指定3种类型的数据:

a string: A string representation of the Link location, created by concatenating the location’s pathname, search, and hash properties. an object: An object that can have any of the following properties: pathname: A string representing the path to link to. search: A string representation of query parameters. hash: A hash to put in the URL, e.g. #a-hash. state: State to persist to the location. a function: A function to which current location is passed as an argument and which should return location representation as a string or as an object

对于你的例子(外部链接):

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

您可以执行以下操作:

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

您还可以传递您想要的道具,如标题,id, className等。

我提供了一个与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 Router中的<Link />组件。

如果你想去外部链接使用锚标签。

<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>
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;