state={
val:0
}
放在定时器了连续执行两次setState
去掉定时器连续执行两次setState
我看到的效果是 放在定时器里的两次setState是同步的 而没有定时器的话 两次setState是异步的。这个有大神帮忙解释一下吗?
state={
val:0
}
放在定时器了连续执行两次setState
去掉定时器连续执行两次setState
我看到的效果是 放在定时器里的两次setState是同步的 而没有定时器的话 两次setState是异步的。这个有大神帮忙解释一下吗?
https://reactjs.org/docs/reac...
setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
以上是官方文档对批量setState的解释,只说了说setState会排队,但实际上,在当前版本中,在不同的地方批量执行setState会有不同的表现。
以下是官方文档中给的一个链接,说明在什么时候setState会被批量处理
In depth: When and why are setState() calls batched?(深入了解:什么时候并且为什么setState()调用会被合并)
Currently (React 16 and earlier), only updates inside React event handlers are batched by default. There is an unstable API to force batching outside of event handlers for rare cases when you need it.
In future versions (probably React 17 and later), React will batch all updates by default so you won't have to think about this. As always, we will announce any changes about this on the React blog and in the release notes.
现在(React 16 和之前),在默认情况下,只有直接在react生命周期React event handlers里写的setState会被合并处理
未来版本(大概从React 17 开始),React会默认合并所有的setState
下面官方文档中给的另一个链接
In depth: Why isn’t this.state updated immediately?(深入了解:为什么this.state没有被立刻更新?)
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答1.9k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
给你一个参考