useLocationSelector
有選擇地從 location 檢索屬性。 僅當您返回的值更改時,此 Hook 才會重新渲染。
有关更多信息,请参阅(https://thisweekinreact.com/articles/useSyncExternalStore-the-undererated-react-api)
useLocationSelector 使用選擇器模式從 window.location 中提取衍生值,僅在選擇器結果變更時重新渲染。它接受一個選擇器函式和一個可選的後備值(用於 SSR),並回傳選擇器的當前輸出。此 hook 監聽導航事件以保持值更新。
使用場景
- 從 URL 中提取特定部分(如路徑名、搜尋參數或雜湊值)以最小化不必要的重新渲染
- 建構根據 URL 的衍生值做出反應的路由感知元件
- 追蹤 URL 的特定部分而不訂閱整個 location 物件
注意事項
- SSR 安全:接受一個
fallback參數,在window.location不可用的伺服器端渲染時回傳。 - 選擇性重新渲染:與直接讀取
window.location不同,選擇器模式確保你的元件僅在衍生值變更時才重新渲染。 - 瀏覽器事件:監聽
window上的popstate事件以偵測前進/後退導航。雜湊變更和pushState/replaceState呼叫也會被追蹤。
Usage
Live Editor
function CurrentPathname() { const pathname = useLocationSelector(location => location.pathname); const ref = useRef(0); useEffect(() => { ref.current = ref.current + 1; }); return ( <div> {pathname} <div>渲染次數:{ref.current}</div> </div> ); } function CurrentHash() { const hash = useLocationSelector(location => location.hash || "無哈希"); const ref = useRef(0); useEffect(() => { ref.current = ref.current + 1; }); return ( <div> {hash} <div>哈希渲染:{ref.current}</div> </div> ); } function Links() { return ( <div> <a href="#link1">#link1</a> <a href="#link2">#link2</a> <a href="#link3">#link3</a> </div> ); } function Demo() { return ( <div> <CurrentPathname /> <CurrentHash /> <Links /> </div> ); } render(<Demo/>)
Result
API
useLocationSelector
Returns
R | undefined
Arguments
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| selector | 选择器 | (location: Location) => R (必填) | - |
| fallback | 默认值 | R | undefined | - |