最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - debounce on react got e.target.value undefined - Stack Overflow

programmeradmin3浏览0评论

Was trying to debounce an input using lodash's debounce, but below code gave me value of 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" />
  }

}

Was trying to debounce an input using lodash's debounce, but below code gave me value of 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" />
  }

}
Share Improve this question asked Mar 3, 2018 at 5:52 Sharon ChaiSharon Chai 5171 gold badge6 silver badges20 bronze badges 2
  • Possible duplicate? Look especially at the section on event pooling for your case stackoverflow./questions/23123138/… – kingdaro Commented Mar 3, 2018 at 5:56
  • @kingdaro I followed the thing correctly, pare my code pls, do not simply paste a link – Sharon Chai Commented Mar 3, 2018 at 6:13
Add a ment  | 

1 Answer 1

Reset to default 15

This happens because of event pooling on the React side.

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.

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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

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

发布评论

评论列表(0)

  1. 暂无评论