debounce on react got e.target.value undefined



试图使用 lodash 的去抖动来解跳输入,但下面的代码给了我未定义的值。

const { debounce } from 'lodash'
class App extends Component {
  constructor(){
    super()
    this.handleSearch = debounce(this.handleSearch, 300)
  }
  handleSearch = e => console.log(e.target.value)
  render() {
    return <input onChange={e => this.handleSearch(e)} placeholder="Search" />
  }
}

发生这种情况是因为 React 端的事件池。

合成事件已池化。这意味着合成事件 对象将被重用,并且在 已调用事件回调。这是出于性能原因。如 因此,您无法以异步方式访问事件。

function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};
class App extends React.Component {
  constructor() {
    super()
    this.handleSearch = debounce(this.handleSearch, 2000);
  }
  handleSearch(event) {
    console.log(event.target.value);
  }
  render() {
    return <input onChange = {
      (event)=>{event.persist(); this.handleSearch(event)}
    }
    placeholder = "Search" / >
  }
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

https://reactjs.org/docs/events.html#event-pooling

最新更新