[英]debounce Lodash - react native
我想在我的文本輸入(React Native App)中使用 loadash debounce。
為什么我的 debounce 工作不正常? 當我按退格鍵時,textInput 中的輸入值消失/重新出現。
handleSearch(text, bool){
// search logic here
}
<TextInput
value={value}
onChangeText={_.debounce((text) =>{this.handleSearch(text, true);this.setFlat(true);this.renderDropDown(false)},200)}
onKeyPress={({ nativeEvent }) => {
if (nativeEvent.key === 'Backspace' && value !== "") {
this.handleClearText();
}
if (nativeEvent.key === 'Backspace' && value === "") {
this.handleClearFilter();
}
}}
/>
class MyComponent extends React.Component {
constructor() {
this.onChangeTextDelayed = _.debounce(this.onChangeText, 2000);
}
onChangeText(text) {
console.log("debouncing");
}
render() {
return <Input onChangeText={this.onChangeTextDelayed} />
您沒有按原意使用回調。 如果你保持這樣,每次你的組件被渲染時,這段代碼就會被執行,除非那個渲染是因為那個事件而被觸發的。
您應該將該代碼移至方法/函數,並將該方法/函數指定為回調。 像這樣的東西:
const handleTextChange = _.debounce((text) =>{
this.handleSearch(text,true);
this.setFlat(true);
this.renderDropDown(false)
},200);
/* .... */
<TextInput
value={value}
onChangeText={handleTextChahge}
/>
你如何導入loadash? 你能試試這個嗎?
import debounce from 'lodash.debounce';
<TextInput
value={value}
onChangeText={debounce((text) => {
this.handleSearch(text,true);
this.setFlat(true);
this.renderDropDown(false)
}, 300)}
placeholder={placeholder}
style={styles.textInput}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.