如何从 useState Hook 中像 setState 一样访问回调

How To Access Callback Like in setState from useState Hook

有没有人设法在 React 16.8 中为 useState 挂钩的更新部分创建同步回调?我一直在寻找一个,以便我可以处理与第 3 方库的同步操作,但我似乎无法满足我的需要。

如果有人对已成功完成此任务的人员有任何参​​考,请在此处添加。

干杯,

有了钩子,您不再需要来自 setState 函数的回调。现在,您可以使用 useState 挂钩设置状态,并使用 useEffect 挂钩监听其值以进行更新。 useEffect 挂钩的可选第二个参数采用一组值来侦听更改。在下面的示例中,我们只监视一个值的变化:

const Example = () => {
  const [value, setValue] = useState(null);

  useEffect(() => {
    // do something when value changes
  }, [value]);

  return (
    <button onClick={() => setValue('Clicked!')}>
      Click Me!
    </button>
  );
};

详细了解 useEffect 挂钩 here

您可以使用 useEffect/useLayoutEffect 来实现:

const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

如果您正在寻找开箱即用的解决方案,请查看 this custom hook,它的工作方式与 useState 相似,但接受回调函数作为第二个参数:

import useStateWithCallback from 'use-state-with-callback';

const SomeOtherComponent = () => {
  const [count, setCount] = useStateWithCallback(0, count => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  });

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

可以通过npm install use-state-with-callback

安装

如果要进行同步布局更新,请改用import { useStateWithCallbackInstant } from 'use-state-with-callback';