如何从 useState Hook 访问像 setState 中的回调 [英] How To Access Callback Like in setState from useState Hook

查看:52
本文介绍了如何从 useState Hook 访问像 setState 中的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Has anyone managed to create a sync callback for the update piece of the useState hook in react 16.8? I have been looking for one so that I can deal with synchronous actions with a 3rd party library and I can't seem to make one work for my needs.

如果有人提及已成功完成此操作的人员,请在此处添加.

If anyone has any references to people that have successfully completed this please add them here.

干杯,

推荐答案

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

With hooks, you no longer need a callback from the setState function. Now, you can set state with the useState hook, and listen for its value to update with the useEffect hook. The optional second parameter of the useEffect hook takes an array of values to listen to for changes. In the example below, we are just monitoring one value for changes:

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

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

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

此处阅读有关 useEffect 钩子的更多信息.

Read more about the useEffect hook here.

这篇关于如何从 useState Hook 访问像 setState 中的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆