30秒学会 React 片段 · 2023年7月12日

30秒学会 React 片段 – React useHash hook

Tracks the browser’s location hash value, and allows changing it.

  • Use the useState() hook to lazily get the hash property of the Location object.
  • Use the useCallback() hook to create a handler that updates the state.
  • Use the useEffect() hook to add a listener for the 'hashchange' event when mounting and clean it up when unmounting.
  • Use the useCallback() hook to create a function that updates the hash property of the Location object with the given value.

代码实现

const useHash = () => {
  const [hash, setHash] = React.useState(() => window.location.hash);

  const hashChangeHandler = React.useCallback(() => {
    setHash(window.location.hash);
  }, []);

  React.useEffect(() => {
    window.addEventListener('hashchange', hashChangeHandler);
    return () => {
      window.removeEventListener('hashchange', hashChangeHandler);
    };
  }, []);

  const updateHash = React.useCallback(
    newHash => {
      if (newHash !== hash) window.location.hash = newHash;
    },
    [hash]
  );

  return [hash, updateHash];
};

使用样例

const MyApp = () => {
  const [hash, setHash] = useHash();

  React.useEffect(() => {
    setHash('#list');
  }, []);

  return (
    <>
      <p>window.location.href: {window.location.href}</p>
      <p>Edit hash: </p>
      <input value={hash} onChange={e => setHash(e.target.value)} />
    </>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <MyApp />
);

翻译自:https://www.30secondsofcode.org/react/s/use-hash