且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在反应中使用带有useState钩子的回调

更新时间:2022-10-19 11:19:18

You can use useEffect/useLayoutEffect to achieve this:

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>
  );
};

More about it over here.

If you are looking for an out of the box solution, check out this custom hook that works like useState but accepts as second parameter a callback function:

// npm install use-state-with-callback

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>
  );
};

相关文章
其他开发最新文章
热门教程
热门工具
上一篇 : :Android的MediaPlayer的错误(-38,0)&QUOT;停止叫状态0&QUOT;下一篇 : JavaScript - 未捕获的SyntaxError:意外的令牌?

相关阅读

技术问答最新文章