这更像是一种提出问题的建议!我有一个搜索框,用户可以在其中输入内容并获得可供选择的建议列表。我正在使用 React,axios 进行数据获取,使用 redux-saga 进行状态管理。它基本上是这样的:
handleChange(stringValue){
this.setState({
inputValue : stringValue
});
callServer(stringValue);
}
现在,一切正常,但问题是发送所有这些请求并处理传入的响应和更改状态似乎是不必要的,因为用户不会停下来查看他键入的每个字符中的建议。我正在寻找一种只在我知道用户完成快速打字时才征求建议的方法。我想做的事情看起来像这样:
handleChange(stringValue){
clearTimeOut(this.callerTimer);
this.callerTimer = null;
this.callerTimer = setTimeOut(function(){
this.callServer(stringValue);
this.callerTimer = null;
}.bind(this),300)
//i consider 300ms as the average time it takes people to stop typing and think
}
这行得通,但我对此感觉不太好。那么你们知道任何其他干净且不太及时的方法来做我想做的事吗?有没有什么方法可以在我的传奇效果中处理这个问题,或者我不知道的输入中的内置时间阈值?
最佳答案
您需要去抖动功能。
基本上,它限制了函数触发的速率。因此,它会等待几 ms,然后再触发事件,就像用户停止写入过程一样。
检查这个片段
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
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);
};
};
// This will apply the debounce effect on the keyup event
// And it only fires 500ms or half a second after the user stopped typing
$('#testInput').on('keyup', debounce(function () {
alert('typing occurred');
$('.content').text($(this).val());
}, 500));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="testInput" />
<p class="content"></p>
检查这个codesandbox对于 React 解决方案
https://codesandbox.io/embed/green-meadow-16r3p?fontsize=14
现在基本上由您决定。以 ms 为单位设置您自己的时间,您就可以开始了。无需为您的项目安装任何其他依赖项。 Lodash 具有去抖动功能,但您不想只为一个功能安装所有的 lodash。
关于javascript - 请求后端输入更改数据的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56849253/