useLocationSelector
有选择地从 location
检索属性。 仅当您返回的值更改时,此 Hook 才会重新渲染。
有关更多信息,请参阅(https://thisweekinreact.com/articles/useSyncExternalStore-the-undererated-react-api)
Usage
实时编辑器
function CurrentPathname() { const pathname = useLocationSelector(location => location.pathname); const ref = useRef(0); useEffect(() => { ref.current = ref.current + 1; }); return ( <div> {pathname} <div>renderCount: {ref.current}</div> </div> ); } function CurrentHash() { const hash = useLocationSelector(location => location.hash || "nohash"); const ref = useRef(0); useEffect(() => { ref.current = ref.current + 1; }); return ( <div> {hash} <div>hashRender: {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/>)
结果
Loading...
API
useLocationSelector
Returns
R | undefined
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
selector | 选择器 | (location: Location) => R (必填) | - |
fallback | 默认值 | R | undefined | - |