javascript - React-Router 外部連結
由於我正在使用 React Router 來處理 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"
}
答案#1
這裡有一行程式碼用來使用 React Router 重定向到外部連結:
<Route path='/privacy-policy' component={() => {
window.location.href = 'https://example.com/1234';
return null;
}}/>
它使用 React 純元件的概念,將元件的程式碼簡化為單一函數,該函數不進行任何渲染,而是將瀏覽器重定向到外部 URL。
它在 React Router 3 和 4 上都可以運作。
答案#2
使用 react-router 的 Link 元件你可以做到這一點。在 "to" 屬性中,你可以指定三種類型的資料:
- a string:連結位置的字串表示法,透過串接該位置的 pathname、search 和 hash 屬性所建立。
一個物件:一個可以擁有以下任意屬性的物件:
- pathname:表示要鏈接的路徑的字符串。
- search:查詢參數的字串表示。
- hash:用於 URL 的哈希值,例如 #a-hash。
- state:要保存到該位置的狀態。
針對你的範例(外部連結):
https://example.zendesk.com/hc/zh-tw/articles/123456789-隱私政策
你可以做以下事情:
<Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />
你也可以傳遞你希望放在 上的屬性,例如 title、id、className 等等。
答案#3
沒有任何需要使用來自 React Router 的 <Link /> 元件。
如果你想要連結到外部連結,請使用錨點標籤。
<a target='_blank'
rel='noopener noreferrer' href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>
對每個連結使用 rel="noopener" 或 rel="noreferrer" 連結屬性。rel="noreferrer" 連結屬性也與 "noopener" 連結屬性具有相同的功能,它可以防止被連結的網站控制連結網站。
答案#4
它不需要請求 React Router。這個操作可以原生完成,並且由瀏覽器提供。
只需使用 window.location。
使用 React Hooks
const RedirectPage = () => {
React.useEffect(() => {
window.location.replace('https://www.google.com')
}, [])
}
使用 React 類別組件
class RedirectPage extends React.Component {
componentDidMount(){
window.location.replace('https://www.google.com')
}
}
另外,如果你想在新分頁中打開它:
window.open('https://www.google.com', '_blank');
答案#5
我實際上最後自己建了一個元件,<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 中並不這麼簡單
