[英]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.