直接使用使用效果中包含的几个状态

发布于 2025-02-12 20:10:04 字数 355 浏览 0 评论 0原文

考虑依赖性阵列中具有2个不同状态的使用效应。每当两种状态中的任何一个更新时,使用效果挂钩都会运行,但是如果我更新其中一个状态,我是否可以访问其他内部使用效果的最后值?如果没有,最好的方法是什么?

function Component() {
  const [state1, setState1] = useState('');
  const [state2, setState2] = useState('');

  useEffect(() => {
    console.log(state1, state2)
  }, [state1, state2]);
  
  return <>...</>
}

Considering an useEffect with 2 different states in the dependency array. The useEffect hook will run whenever any of those two states are updated, but if i update one of them, will i have access to the lastest value of the other inside useEffect? And if not, what is the best approach to it?

function Component() {
  const [state1, setState1] = useState('');
  const [state2, setState2] = useState('');

  useEffect(() => {
    console.log(state1, state2)
  }, [state1, state2]);
  
  return <>...</>
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伪心 2025-02-19 20:10:04

使用内部的回调将根据依赖项数组有条件地渲染后运行。
如果您的状态值在相同的渲染周期中更新,则将它们进行批处理(通过React),并且下一个渲染周期将在useFeffect回调中显示正确的值。

如果仅更新其中任何一个,则不必担心另一个值,因为useffect中的回调也将使用其他变量的最近更新值。

注意:您唯一可能面临的问题是当您由于关闭而具有陈旧的状态值时,这是一种特定情况。

The callback inside useEffect will run after the render conditionally based on dependency array.
If your state values are updated in the same render cycle then they are batched (by React) and the next render cycle will show both the correct values in the useEffect callback.

If you only update any one of them, you do not have to worry about the other value because the callback in useEffect will be using the recently updated value of the other variable too.

Note: The only time you might face an issue is when you have stale state values because of closure, but that is a specific case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文