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

标签 javascript html google-chrome reactjs listener

我有这样的代码:

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/

相关文章:

javascript - 如何循环遍历 Firebase 文档以查找匹配文档,然后提取名称?

Javascript 结果到 div

javascript - HTML 源字段还将 html 代码更改为转义字符

javascript - Chrome 扩展消息传递

javascript - jQuery - 如果打开任何激活元素,如何隐藏元素?

javascript - 使用流将文件保存到 azure 存储不起作用

html - 有效的字体系列名称

javascript - 为什么JS代码不起作用?

google-chrome - 处理chrome的rtp流需要哪些gstreamer管道设置?

java - Selenium webdriver .click() 方法在 Chrome 浏览器中失败