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

当前回答

为了扩展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
}}/>

其他回答

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

为了扩展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
}}/>

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

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

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

在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;

我自己解决了这个问题(在我的web应用程序中),通过添加一个锚标记,而不是使用React路由器的任何东西,只是一个普通的锚标记和一个链接,正如你可以在图片截图中看到的,在一个React应用程序中使用锚标记而不使用React路由器

基本上,你不会将你的用户路由到你的应用程序中的另一个页面,所以你不能使用内部路由器,而是使用一个正常的锚。

虽然这是一个非反应本机解决方案,但您可以尝试。