为什么 React useState 钩子不能在 for 循环中工作? [英] Why doesn't the React useState hook work in a for loop?

查看:771
本文介绍了为什么 React useState 钩子不能在 for 循环中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么在 for 循环中设置状态没有按预期工作.

I'm curious about why setting state in a for loop doesn't work as expected.

这是我使用钩子的代码.

This is my code using hooks.

const [count, setCount] = useState(0);

  const onButtonPress = () => {
    for(let i=0; i<100; i++){
      setCount(i);
    }
  }

  useEffect(()=> {
    console.log('useEffect called');
    console.log(count);
  },[count])

我在单击按钮时调用 onButtonPress 函数.

I call the onButtonPress function on a button click.

我期望的行为:计数状态 shhoukd 更新 100 次,因此调用 useEffect 钩子 100 次.

Behavior I expect: count state shoukd update 100 times and consequently call the useEffect hook a 100 times.

实际行为:useEffect 钩子在循环的最后一次迭代后只被调用一次.

Actual behavior: The useEffect hook is being only called once after the last iteration of the loop.

我知道官方 react 文档说不应该在循环中使用钩子,但他们的解释不是很清楚.

I know that the official react docs say that hooks shouldn't be used in loops but their explanation isn't very clear.

我想了解为什么在循环中调用 setCount 不起作用.

I want to understand why calling setCount in a loop doesn't work.

注意:我知道还有其他方法可以达到预期的结果,但我有兴趣了解为什么不会多次调用 setCount.

NOTE: I know that there are other methods to achieve the desired result but I'm interested in understanding why the setCount wouldn't be called multiple times.

推荐答案

React 批量调度状态更改,当运行 for 循环时,它会快速批量处理 100 个请求,导致只有 1 次状态更新并最终重新渲染 1 次.如果您使用 0ms 的 setTimeout 事件,您将能够获得所需的但我不完全确定您的用例.

React dispatches the state changes in batch, when running a for loop it quickly batches 100 requests resulting in only 1 state update and eventually 1 re-render. If you use setTimeout event with 0ms, you'd able to get the required but I'm not totally sure about your use-case.

这篇关于为什么 React useState 钩子不能在 for 循环中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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