簡體   English   中英

react-router:如何在不導致導航/重新加載的情況下更新 url?

[英]react-router: How do I update the url without causing a navigation/reload?

使用 React 路由器,我已經更新了 url:

this.props.history.push({
            pathname: `/product/${this.props.product.id}`,
        });

然而,這會導致重新渲染/導航更改。 有沒有辦法在不這樣做的情況下更新 url?

我的用例是我有一個產品列表,當我單擊一個產品時,我會顯示一個模態窗口,並希望將 url 更新為 example.com/product/1 之類的內容,以便可以共享該鏈接。

無法使用 React Router 找到解決方案,但能夠使用瀏覽器的歷史界面通過調用:

window.history.replaceState(null, "New Page Title", "/pathname/goes/here")

您可以在此處了解有關.replaceState的更多信息。

React Router 的history.replace並不總是有效

React Router 的history.replace方法可能會也可能不會觸發重新渲染,具體取決於您的應用程序的路由設置(例如,您有一個包羅萬象的/*路由)。 它不會根據定義阻止渲染。

替換將覆蓋 URL

this.props.history.replace({ pathname: `/product/${this.props.product.id}`})

我正在使用一種很好的方式來欺騙用戶,即 URL 不會改變。

為此,您只需要像這樣設置您的路線。

const Home = '/';
const About = '/ ';
const Contact = '/  ';

注意空格。 所有字符都將計入引號內,因此它應該可以工作。

Routes.tsx

<Route exact path={Home} component={Home} />
<Route exact path={About} component={About} />
<Route exact path={Contact} component={Contact} />

在您的About.tsxContact.tsx中:

  useEffect(() => {
    window.history.replaceState(null, '', Home);
  }, []);

用戶導航到AboutContact頁面后,將調用掛鈎並運行回調函數內的代碼。 它將在組件渲染后刪除空格。

這應該是偽裝隱藏 URL 的干凈技巧😂

舊帖子,但我想我不妨回答一下。 我認為您正在尋找的是useHistory()鈎子。

用法:

import { useHistory } from "react-router-dom";

const history = useHistory();
history.push("/my/url");

當您在反應組件中時, props具有history ,您可以使用它。

對於那些即使不在反應組件內部也正在尋找一種導航方式的人,即您無法獲得props.history ,這是一種方法:

在渲染路由器的組件中:

// outside the component
export const browserRouterRef = React.createRef();

// on render
<BrowserRouter ref={browserRouterRef}>

然后,您可以在任何地方導入browserRouterRef並使用browserRouterRef.current.history更改路由,即使您不在反應組件中。

暫無
暫無

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

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