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

当前回答

补充一下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。

其他回答

我能够在react-router-dom中使用以下方法实现重定向

<Route exact path="/" component={() => <Redirect to={{ pathname: '/YourRoute' }} />} />

对于我的案例,我正在寻找一种方法,每当用户访问根URL http://myapp.com时,将他们重定向到应用程序http://myapp.com/newplace中的其他地方。因此,上述方法有所帮助。

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中使用http://或https://解决了它。

像: <a target="_blank" href="http://www.example.com/" title="example">见detail</a>

我也遇到过同样的问题。我希望我的投资组合重定向到社交媒体处理。之前我使用了"react-router-dom"中的{Link}。重定向到这里的子目录,

链接可用于在网站内路由网页。如果我们想重定向到一个外部链接,那么我们应该使用一个锚标记。像这样,

在React Route V6中,渲染道具被移除。它应该是一个重定向组件。

重定向网址:

const RedirectUrl = ({ url }) => {
  useEffect(() => {
    window.location.href = url;
  }, [url]);

  return <h5>Redirecting...</h5>;
};

路线:

<Routes>
   <Route path="/redirect" element={<RedirectUrl url="https://google.com" />} />
</Routes>