Warning: This synthetic event is reused for performance reasons.

简介: Warning: This synthetic event is reused for performance reasons.

正文


444.webp.jpg配图源自 Freepik


可能大家在 react 开发中,会遇到以下报错:


Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See https://fb.me/react-event-pooling for more information.


例子


// 其他无关紧要部分省略了
<input onChange={event => {
  console.log(event.type)  // change
  setTimeout(() => {
    console.log(event.type)  // null,并会出现以上警告
  })
}} />


Why


首先,我们的事件处理程序将传递 SyntheticEvent 实例,这是一个跨浏览器原生事件包装器。它具有与浏览器原生事件相同的接口,包括 stopPropagation()preventDefault(),除了事件在所有浏览器中它们的工作方式都相同


每个 SyntheticEvent 对象都具有以下属性:


boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
boolean isDefaultPrevented()
void stopPropagation()
boolean isPropagationStopped()
DOMEventTarget target
number timeStamp
string type


SyntheticEvent 对象是通过合并得到的。出于性能原因的考虑,SyntheticEvent 对象将被重用并且所有属性都将被取消,因此,无法以异步方式访问该事件。

所以,我们异步访问 event.type 时会得到 null 值,那么怎么破呢?


如果要以异步方式访问事件属性,应该对事件调用 event.persist(),这将从池中删除合成事件,并允许用户代码保留对事件的引用。


异步调用方式


// 其他无关紧要部分省略了
<input onChange={event => {
  console.log(event.type)  // change
  event.persist()
  setTimeout(() => {
    console.log(event.type)  // change,能正常访问了
  })
}} />


参考


更详细请查看 合成事件(SyntheticEvent)



目录
相关文章
|
Rust 小程序
小程序警告:Now you can provide attr wxkey for a wxfor to improve performance
首先,无论什么程序,控制台中的警告都是会影响程序性能的。我们需要减少此类警告的出现,以提高程序的运行性能。 小程序开发的时候,遇到了如下的警告:
165 0
|
Java Maven
An attempt was made to call a method that does not exist. The attempt was made from the following
An attempt was made to call a method that does not exist. The attempt was made from the following
467 0
|
JavaScript 前端开发
Guidelines for Function Compute Development - Troubleshoot Timeout Issues
Endless codes and endless bugs When you write code, you may inadvertently introduce some hidden bugs, even if you test a large proportion of the codes to the maximum extent possible.
1641 0