跳至主要内容

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>渲染次數:{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/>)
結果
/zh-Hant/browser/useLocationSelector
渲染次數:0
無哈希
哈希渲染:0

API

useLocationSelector

Returns

R | undefined

Arguments

參數名描述類型預設值
selector选择器(location: Location) => R (必填)-
fallback默认值R | undefined-
ads via Carbon