由于我在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 v4兼容。

它使用的是TypeScript,但转换为原生JavaScript应该相当简单:

interface Props {
  exact?: boolean;
  link: string;
  path: string;
  sensitive?: boolean;
  strict?: boolean;
}

const ExternalRedirect: React.FC<Props> = (props: Props) => {
  const { link, ...routeProps } = props;

  return (
    <Route
      {...routeProps}
      render={() => {
        window.location.replace(props.link);
        return null;
      }}
    />
  );
};

与…一起使用:

<ExternalRedirect
  exact={true}
  path={'/privacy-policy'}
  link={'https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}
/>

其他回答

利用这里的一些信息,我提出了以下组件,您可以在路由声明中使用它。它与React Router v4兼容。

它使用的是TypeScript,但转换为原生JavaScript应该相当简单:

interface Props {
  exact?: boolean;
  link: string;
  path: string;
  sensitive?: boolean;
  strict?: boolean;
}

const ExternalRedirect: React.FC<Props> = (props: Props) => {
  const { link, ...routeProps } = props;

  return (
    <Route
      {...routeProps}
      render={() => {
        window.location.replace(props.link);
        return null;
      }}
    />
  );
};

与…一起使用:

<ExternalRedirect
  exact={true}
  path={'/privacy-policy'}
  link={'https://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"/>}/>

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

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

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

下面是使用React Router重定向到外部链接的一行代码:

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

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

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

如果你使用服务器端渲染,你可以使用StaticRouter。用你的上下文作为道具,然后在你的应用程序中添加<重定向路径="/somewhere" />组件。这个想法是每次React路由器匹配一个重定向组件时,它会添加一些东西到你传递到静态路由器的上下文中,让你知道你的路径匹配一个重定向组件。

现在你知道你点击了一个重定向,你只需要检查这是否是你正在寻找的重定向。然后通过服务器重定向。ctx.redirect(“https://example/com”)。