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
若是有錯誤或者不嚴謹的地方,請務必給予指正,十分感謝!異步