[英]How to make autocomplete faster and smoother in React/Redux?
I've implemented a search bar with autocomplete. 我已经实现了带有自动完成功能的搜索栏。
The input component has an onChange property that triggers off an action creator that makes a GET request to my DB to fetch autocomplete suggestions. 输入组件具有onChange属性,该属性触发一个动作创建者,该动作创建者向我的数据库发出GET请求以获取自动完成建议。
I'm then returning and rendering the entire action.payload each time. 然后,我每次返回并渲染整个action.payload。
onInputChange : onInputChange :
onInputChange(event) {
this.setState({ term: event.target.value });
if (event.target.value.length >= 3) {
setTimeout(this.props.fetchSuggestions(event.target.value), 1000);
}
}
fetchSuggestions (action creator): fetchSuggestions (动作创建者):
export const fetchSuggestions = (term) => async dispatch => {
const res = await axios.get(`${BASE_URL}/api/symptoms?query=${term}`);
dispatch({
type: constants.FETCH_SUGGESTIONS,
payload: res.data
});
}
symptomSuggestions (reducer): 症状建议 (减少剂):
export default function(state = [], action) {
switch (action.type) {
case FETCH_SUGGESTIONS:
return action.payload;
default:
return state;
}
}
At the moment I've limited queries to length 3 or more and querying every 1s to limit the API calls I make to the database. 目前,我已将查询的长度限制为3个或更多,并且每1秒查询一次以限制对数据库的API调用。
Given this implementation, are there any other ways I can improve the autocomplete feature to make it less laggy? 有了这种实现方式,我还有其他方法可以改善自动完成功能,以减少延迟吗?
You can try to add some debounce. 您可以尝试添加一些去抖动功能。 Something like: 就像是:
let lastFetched = 0;
onInputChange(event) {
this.setState({ term: event.target.value });
if (event.target.value.length >= 3 && (new Date() - new Date(lastFetched )) > 300) {
lastFetched = Date.now();
this.props.fetchSuggestions(event.target.value);
}
}
This way you woun't be sending request every time that user types every single character, but only after slight period, after he finished typing. 这样,您不会在用户每次键入每个字符时都发送请求,而只是在稍等片刻之后,即他完成键入后,才发送请求。
可能矫kill过正,但是RxJS(又名Redux-observable)已经消除了内置的抖动,以及许多其他可以节流的运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.