簡體   English   中英

如何查看 React Router v6 中的查詢字符串是否發生變化?

[英]How to watch if the querystring changes within React Router v6?

我有一個帶有下拉列表的表單,當我 select 下拉列表時,我將值推送到查詢字符串上。 當第一次命中帶有該查詢字符串的 url 時,它將查詢字符串參數存儲到 state 中,然后使用它來填充下拉列表。 這一切都按預期工作。 我的問題是觸發表單以在同一頁面上查看查詢字符串的更改。

如果我已經在頁面上但是然后單擊反應路由器鏈接到同一頁面但使用不同的查詢字符串參數它不會捕獲/看到它已更改。 我想知道如何查看查詢字符串的更改,或者是否有更好的方法來處理這個問題。

I've found that you can listen to the history object that React-Router is meant to use under the hood but I've had little success with this and again I'm not sure if this is the right way to go https://github .com/ReactTraining/history/blob/master/docs/getting-started.md

我嘗試將以下內容添加到頁面,但是當我更改 url 的查詢字符串(又名搜索)時,監聽器似乎永遠不會觸發。 想知道我錯過了什么嗎?

  useEffect(() => {
    // Listen for changes to the current location.
    console.info("wiring up history listener");
    let unlisten = history.listen(({ location, action }) => {
      console.info("HISTORY CHANGED", location.search);
      console.log(action, location.pathname, location.state);
      // Plan was to update my state here if needed
    });

    return unlisten;
  }, []);

如果你想監聽路徑查詢字符串參數的變化,你需要從 object位置“監聽”它們的變化。 使用useLocation鈎子獲取location object。

location

 { key: 'ac3df4', // not with HashHistory: pathname, '/somewhere': search? ',some=search-string': hash, '#howdy': state: { [userDefined]: true } }

使用效果掛鈎監聽變化。

const { search } = useLocation();

useEffect(() => {
  // search query string changed
}, [search]);

react-router 配有您需要的所有掛鈎 聽起來像你想要的: useParams

您的代碼不起作用,因為react-router使用不同的history實例,因此當通過react-routerLink進行更改時不會觸發您的自定義偵聽器(它由不同版本的history處理)。 但是,單擊瀏覽器的前進或后退按鈕應該會觸發您的偵聽器,因為這會通知所有history實例。

適合您的用例的最佳工具是useSearchParams掛鈎

const [searchParams] = useSearchParams();

useEffect(() => {
  // code for handling search query change
}, [searchParams]);

此外,您可能不需要使用useEffect ,而是將searchParams視為搜索數據的真實來源,而無需在 state 中創建另一個實體。

暫無
暫無

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

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