[英]Trying to debounce search function calls results in no event passed to a function
I am working with a library named lodash using its debounce()
function to sort of limit api calls for search suggestions ie instead of calling api every time user changes a field I debounce it and wait 300ms from when they finish typing: 我正在使用名为lodash的库,使用它的debounce
debounce()
函数对搜索建议的限制api调用进行排序,即不是每次用户更改字段时都调用api,而是对它进行反抖动并等待输入完成后等待300毫秒:
it looks like this in my component: 在我的组件中看起来像这样:
class myComponent extends Component {
//Handle listing search
searchListing(event) {
console.log(event.target.value);
}
//Render
render() {
const listingSearch = _.debounce( () => { this.searchListing() }, 300 );
return (
<TextInput onChange={listingSearch}/>
);
}
}
it works and calls the function however I get an error saying: Uncaught TypeError: Cannot read property 'target' of undefined
它可以正常工作并调用该函数,但是我收到一条错误消息:
Uncaught TypeError: Cannot read property 'target' of undefined
So I tried passing an event like so: 所以我试着通过这样的事件:
const listingSearch = _.debounce( (event) => { this.searchListing(event) }, 300 );
Now error says: Uncaught TypeError: Cannot read property 'value' of null
after inspecting this event I'm passing, I can see that it has empty target, so is not working correctly. 现在错误说:
Uncaught TypeError: Cannot read property 'value' of null
检查我传递的此事件后Uncaught TypeError: Cannot read property 'value' of null
,我可以看到它具有空目标,因此无法正常工作。
Solution to my problem was to include event.persist();
解决我的问题的方法是包括
event.persist();
inside my onChange handler function. 在我的onChange处理函数中。
So: 所以:
searchListing(event) {
event.persist();
console.log(event.target.value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.