簡體   English   中英

React-Router 外部鏈接

[英]React-Router External link

由於我使用 react-router 在 React 應用程序中處理我的路由,我很好奇是否有辦法重定向到外部資源。

說有人打:

example.com/privacy-policy

我希望它重定向到:

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

我發現完全零幫助避免在我的 index.html 加載類似的東西:

if ( window.location.path === "privacy-policy" ){
  window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}

這是使用 React Router 重定向到外部鏈接的單行代碼:

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

它使用 React 純組件概念將組件的代碼簡化為單個函數,而不是渲染任何內容,而是將瀏覽器重定向到外部 URL。

適用於 React Router 3 和 4。

使用 react-router 的 Link 組件,您可以做到這一點。 在 " to " 道具中,您可以指定 3 種類型的數據:

  • a string :鏈接位置的字符串表示形式,通過連接位置的路徑名、搜索和哈希屬性創建。
  • 對象:可以具有以下任何屬性的對象:
    • pathname : 表示要鏈接到的路徑的字符串。
    • search :查詢參數的字符串表示形式。
    • hash : 放在 URL 中的哈希,例如 #a-hash。
    • state : 堅持到該位置的狀態。
  • 一個函數:一個函數,當前位置作為參數傳遞給它,它應該以字符串或對象的形式返回位置表示

對於您的示例(外部鏈接):

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 中的<Link />組件。

如果您想轉到外部鏈接,請使用錨標記。

<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>

它不需要請求反應路由器。 此操作可以在本地完成,並且由瀏覽器提供。

只需使用window.location

class RedirectPage extends React.Component {
  componentDidMount(){
    window.location.replace('https://www.google.com')
  }
}

另外,如果您想在新選項卡中打開它:

window.open('https://www.google.com', '_blank');

我實際上最終構建了自己的組件。 <Redirect>它從react-router元素獲取信息,所以我可以將它保存在我的路由中。 如:

<Route
  path="/privacy-policy"
  component={ Redirect }
  loc="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies"
  />

這是我的組件,以防萬一有人好奇:

import React, { Component } from "react";

export class Redirect extends Component {
  constructor( props ){
    super();
    this.state = { ...props };
  }
  componentWillMount(){
    window.location = this.state.route.loc;
  }
  render(){
    return (<section>Redirecting...</section>);
  }
}

export default Redirect;

編輯 - 注意:這是使用react-router: 3.0.5 ,在 4.x 中並不是那么簡單

使用這里的一些信息,我想出了以下組件,您可以在路由聲明中使用它。 它與 React Router v4 兼容。

它使用打字稿,但轉換為原生 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'}
/>

我很幸運:

  <Route
    path="/example"
    component={() => {
    global.window && (global.window.location.href = 'https://example.com');
    return null;
    }}
/>

我不認為 React-Router 提供這種支持。 文檔提到

< Redirect > 設置重定向到應用程序中的另一個路由以維護舊 URL。

你可以嘗試使用React-Redirect 之類的東西

最簡單的解決方案是使用渲染函數並更改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>

要擴展 Alan 的答案,您可以創建一個<Route/>將所有<Link/>重定向到包含“http:”或“https:”的“to”屬性到正確的外部資源。

下面是一個可以直接放入您的<Router>的工作示例。

<Route path={['/http:', '/https:']} component={props => {
  window.location.replace(props.location.pathname.substr(1)) // substr(1) removes the preceding '/'
  return null
}}/>

我經歷了同樣的問題。 我希望我的投資組合重定向到社交媒體句柄。 早些時候我使用{Link} from "react-router-dom". 那是重定向到子目錄,如下所示,

在此處輸入圖片說明

鏈接可用於在網站內路由網頁。 如果我們想重定向到外部鏈接,那么我們應該使用錨標記。 像這樣,

在此處輸入圖片說明

我自己解決了這個問題(在我的網絡應用程序中),通過添加一個錨標簽而不使用 React 路由器中的任何東西,只是一個帶有鏈接的普通錨標簽,如在 react.js 中使用錨標簽的圖片截圖所示不使用反應路由器的應用程序

基本上,您不會將用戶路由到應用程序內的另一個頁面,因此您不得使用內部路由器,而應使用普通錨點。

雖然這是針對非反應本機解決方案,但您可以嘗試。

對於 V3,雖然它可能適用於 V4。 離開埃里克的回答,我需要做更多的事情,比如處理 url 上不存在“http”的本地開發。 我還重定向到同一服務器上的另一個應用程序。

添加到路由器文件:

import RedirectOnServer from './components/RedirectOnServer';

       <Route path="/somelocalpath"
          component={RedirectOnServer}
          target="/someexternaltargetstring like cnn.com"
        />

和組件:

import React, { Component } from "react";

export class RedirectOnServer extends Component {

  constructor(props) {
    super();
    //if the prefix is http or https, we add nothing
    let prefix = window.location.host.startsWith("http") ? "" : "http://";
    //using host here, as I'm redirecting to another location on the same host
    this.target = prefix + window.location.host + props.route.target;
  }
  componentDidMount() {
    window.location.replace(this.target);
  }
  render(){
    return (
      <div>
        <br />
        <span>Redirecting to {this.target}</span>
      </div>
    );
  }
}

export default RedirectOnServer;

您可以用於您的動態網址

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

我認為最好的解決方案是使用一個普通的<a>標簽。 其他一切似乎都很復雜。 React router 是為在單頁應用程序中導航而設計的,因此將其用於其他任何事情並沒有多大意義。 為已經內置在<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;

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

在 React Router v6 中, component不可用。 相反,現在它支持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;

在此處補充@víctor-daniel 的答案:僅當鏈接前有“https://”或“http://”時,鏈接的pathname才會將您帶到外部鏈接

您可以執行以下操作:

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

或者,如果您的網址沒有帶有“https://”,我會執行以下操作:

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

否則,它會預先設置當前的基本路徑,正如@lorenzo-dematté 評論的那樣

提供與 react-router v6 相關的答案以處理動態路由。

我創建了一個名為重定向的通用組件:

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

  return (
    <div />

  )
}

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

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

使用 React 和 Typescript 你會得到一個錯誤,因為函數必須返回一個 react 元素,而不是void 所以我使用 Route 渲染方法(並使用 React 路由器 v4)這樣做了:

redirectToHomePage = (): null => {
    window.location.reload();
    return null;
  };    
<Route exact path={'/'} render={this.redirectToHomePage} />

你也可以使用window.location.assign() , window.location.replace()

我面臨同樣的問題。 在 react js 中通過http://https://解決了它。

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

如果您使用服務器端渲染,則可以使用StaticRouter 將您的context作為props ,然后在您的應用程序中添加<Redirect path="/somewhere" />組件。 這個想法是每次 react-router 匹配重定向組件時,它都會在您傳遞給靜態路由器的上下文中添加一些內容,讓您知道您的路徑與重定向組件匹配。 現在您知道您點擊了重定向,您只需要檢查這是否是您正在尋找的重定向。 然后只需通過服務器重定向。 ctx.redirect('https://example/com')

由於我在 React 應用程序中使用 react-router 來處理我的路由,我很好奇是否有辦法重定向到外部資源。

說有人打:

example.com/privacy-policy

我希望它重定向到:

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

我發現在我的 index.html 加載中避免在純 JS 中編寫它的幫助為零,例如:

if ( window.location.path === "privacy-policy" ){
  window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}

您現在可以通過使用pathname鍵提供對象 to to使用 React Link 鏈接到外部站點:

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

如果你發現在回調中需要使用 JS 生成鏈接,可以使用window.location.replace()window.location.assign()

使用window.location.replace() ,正如其他好的答案所建議的那樣,嘗試使用window.location.assign()

window.location.replace()將替換位置歷史記錄而不保留當前頁面。

window.location.assign()將轉換到指定的 url,但會在瀏覽器歷史記錄中保存上一頁,允許適當的后退按鈕功能。

https://developer.mozilla.org/en-US/docs/Web/API/Location/replace https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

另外,如果您使用的是其他答案中提到的window.location = url方法,我強烈建議您切換到window.location.href = url 關於它有一個激烈的爭論,其中許多用戶似乎固執地希望將較新的object類型window.location恢復為string原始實現,僅僅是因為他們可以(並且他們嚴重攻擊任何不這么說的人),但理論上你可以打斷訪問window.location對象的其他庫功能。

看看這個會議。 它是可怕的。 Javascript:設置 location.href 與位置

我能夠使用以下方法在 react-router-dom 中實現重定向

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

就我而言,我一直在尋找一種方法,可以在用戶訪問根 URL http://myapp.com時將用戶重定向到應用程序http://myapp.com/newplace 所以以上幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM