react 合成事件中的异步处理

发布时间:2019-08-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了react 合成事件中的异步处理脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

如果直接将事件处理函数(其中需要修改state)进行debounce装饰就会报如下错误,

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.
SyntheticEvent 对象是通过合并得到的。 这意味着在事件回调被调用后,SyntheticEvent 对象将被重用并且所有属性都将被取消。这是出于性能原因。因此,您无法以异步方式访问该事件。

因为react中的event是池化的合成事件,debounce处理后就是异步操作,所以再次获取event 是空对象。因此将过程拆解,handleEvent 照常处理event 对象再将修改state的操作进行抖即可。

); }); return ( <> delay: {this.props.delay}
{eventCount} ); } }" tITle="" data-original-title="复制">
import React From "react";
import ReactDOM from "react-dom";
import { debounce, get } from "lodash";

import "./styles.css";

export class Mycomponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.genDebounceFn = this.genDebounceFn.bind(this);
  }

  handleEvent(e) {
    const newState = {
      ...this.state
    };
    // 这里引用了SyntheticEvent event 对象的type 方法
    newState[e.type] = get(this.state, e.type, 0) + 1;
    this.modifyState.call(this, newState);
  }

  componentWillReceiveProps(nextProps) {
    this.genDebounceFn(nextProps);
  }

  componentDidmount() {
    this.genDebounceFn(this.props);
  }

  genDebounceFn(props) {
    this.modifyState = debounce(newState => {
      this.setState(() => newState);
    }, props.delay);
  }

  render() {
    const eventCount = Object.keys(this.state).map(e => {
      return (
        <div key={e}>
          {e}:{this.state[e]}
        </div>
      );
    });
    return (
      <>
        delay: {this.props.delay}
        <br />
        <span>{eventCount}</span>
        <button
          onClick={this.handleEvent.bind(this)}
          onMouseOver={this.handleEvent.bind(this)}
        >
          click me OR mouseOver me
        </button>
      </>
    );
  }
}

点击预览

脚本宝典总结

以上是脚本宝典为你收集整理的react 合成事件中的异步处理全部内容,希望文章能够帮你解决react 合成事件中的异步处理所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
猜你在找的React相关文章
全站导航更多
最新React教程
热门React教程