debounce on react得到e.target.value undefined

时间:2018-03-03 05:52:25

标签: javascript reactjs ecmascript-6

试图使用lodash的debounce去抖动输入,但是下面的代码给了我undefined的值。

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" />
  }

}

1 个答案:

答案 0 :(得分:4)

这是因为React端的事件池。

  

汇集SyntheticEvent。这意味着SyntheticEvent   对象将被重用,所有属性将在之后无效   已调用事件回调。这是出于性能原因。如   这样,你就无法以异步方式访问事件。

&#13;
&#13;
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'));
&#13;
<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>
&#13;
&#13;
&#13;

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