gpt4 book ai didi

javascript - 为什么 Chrome 显示的听众数量比实际数量少?

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:55 24 4
gpt4 key购买 nike

我有这样的代码:

function ManyNodes() {
const nums = new Array(1e5).fill(0).map(_ => Math.floor(Math.random()*1e8));
return (
<ul>{nums.map(n => <li key={n} onClick={e=>console.log(n)}>{n}</li>)}</ul>
)
}

render(<ManyNodes />, document.querySelector('#app'))

那么文档中应该有 1e5 li 并且每个 li 都有自己的点击监听器。所以页面上应该有超过 1e5 个监听者。

但我使用 Chrome Web Developer Tool,在其Performance 选项卡中,您只能看到数百个监听器。这很奇怪。

react 如何处理这个问题?

最佳答案

TL;DR 事件委托(delegate)和事件池

事件委托(delegate)

Attaching event listeners to DOM nodes is painfully slow and memory-consuming. Instead, React implements a popular technique called "event delegation".

什么是事件委托(delegate)?

A single event listener is attached to the root of the document. When an event is fired, the browser gives us the target DOM node [...]

供您引用,Vjeux 是 Facebook 软件工程师,在前端团队从事 React Native 工作。

http://blog.vjeux.com/2013/javascript/react-performance.html (查看事件委托(delegate)部分)

事件池

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

https://facebook.github.io/react/docs/events.html

关于javascript - 为什么 Chrome 显示的听众数量比实际数量少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44969163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com