记一次React中异步获取事件对象的爬坑经历

SyntheticEvent objects are pooled

在使用React过程当中,直接异步获取事件对象上的属性,实际上咱们拿到的值永远是null,下面的代码就存在问题缓存

const handleClick = e => {
        setTimeout(() => {
            console.log(e.target.name)
        });
    }

控制台会输出 null。出现上面这种状况,React官方给出的解释以下:异步

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.async

在 React 事件处理中,事件对象被包装在一个 SyntheticEvent(合成事件)对象中。这些对象是被池化的(pooled),这意味着在事件处理程序会把这些对象重用于其余事件以提升性能。随之而来的问题就是,异步访问事件对象的属性是不可能的,由于事件的属性因为重用而被重置(nullified)。性能

解决方式是把事件对象e 赋值到一个内部变量上。this

const handleClick = e => {
    let name = e.target.name;    //   将须要从事件对象上获取的信息,先缓存到变量上面
        setTimeout(() => {
            console.log(name);
        });
    }

React 官方实例code

function onClick(event) {
  console.log(event); // => nullified object.
  console.log(event.type); // => "click"
  const eventType = event.type; // => "click"

  setTimeout(function() {
    console.log(event.type); // => null
    console.log(eventType); // => "click"
  }, 0);

  // Won't work. this.state.clickEvent will only contain null values.
  this.setState({clickEvent: event});

  // You can still export event properties.
  this.setState({eventType: event.type});
}

想异步访问事件属性,能够在事件上调用event.persist(),这会从池中移除合成事件并容许对事件的引用被保留。orm

相关文章
相关标签/搜索