React 中 input 的 onChange 事件 e 参数传递以后 e.target 变为 null

github 的地址 欢迎 starcss

前言

小明遇到了一个需求:在 input 框 change 的时候发起一个异步请求,对于请求通常作法都要防抖,可是却遇到了取不到 value 的值的状况。 简化代码能够查看 这里 关键代码:react

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Input } from "antd";
import _ from "lodash";
const changeValue = e => {
  const value = e.target.value;
  console.log("sdj", e);
  console.log("sdj", value);
  const debugeDebounce = _.debounce(() => {
    fetchAjax(e);
    // fetchAjax(value);
  }, 900);
  debugeDebounce();
};

const fetchAjax = e => {
  console.log("sdj222", e);
};

ReactDOM.render(
  <Input placeholder="Basic usage" onChange={changeValue} />,
  document.getElementById("container")
);

复制代码

在 fetchAjax 中取到的 e.target 为 null 的状况,在其中通过断点调试,发现了其中的原因。git

首先,在 changeValue 中,事件触发,就能获取到 event 对象,其中主要就是 event.target 就是当前触发事件的 dom 对象,因为 debounce 延迟执行,致使了 changeValue 函数已经执行完了,进入了 react-dom 中相关一系列操做(进行了一系列复杂的操做),下面给出最关键的 executeDispatchesAndRelease,executeDispatchesAndRelease 方法释放 event.target 的值github

/**
 * Dispatches an event and releases it back into the pool, unless persistent.
 *
 * @param {?object} event Synthetic event to be dispatched.
 * @private
 */
        var executeDispatchesAndRelease = function(event) {
            if (event) {
                executeDispatchesInOrder(event);
                if (!event.isPersistent()) {
                    event.constructor.release(event);
                }
            }
        };
复制代码

具体的能够本身断点查看相关 event 的值的变化bash

因为 event 在 debounce 中做为了参数,内存中没有清除,执行上面的方法 event.target = null; event 为引用类型,一处改变,全部用到的地方都会改变。致使了 debounce 中 event 也发生了变化。antd

解决

明白了上面的一些知识,就知道应该怎么修改代码了(把用到的值存在一个变量中)less

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Input } from "antd";
import _ from "lodash";
const changeValue = e => {
  const value = e.target.value;
  console.log("sdj", e);
  console.log("sdj", value);
  const debugeDebounce = _.debounce(() => {
  
    -- fetchAjax(e);
    ++ fetchAjax(value);
    
  }, 900);
  debugeDebounce();
};

const fetchAjax = e => {
  console.log("sdj222", e);
};

ReactDOM.render(
  <Input placeholder="Basic usage" onChange={changeValue} />,
  document.getElementById("container")
);

复制代码

总结

工做中的一些问题仍是值得去挖掘的,总会有必定的收获!这个问题中包括了内存释放,引用类型,事件等dom

若是有错误或者不严谨的地方,请务必给予指正,十分感谢!异步

参考

  1. stackoverflow.com/questions/2…
  2. developer.mozilla.org/zh-CN/docs/…
相关文章
相关标签/搜索