【发布时间】:2023-03-03 00:48:01
【问题描述】:
我有以下 onChange 函数
onChange = e => {
this.setState({
autocompleteValues: [],
showPredictivo: true
})
if (e.target.value.length > 3) this.partialSearch(e.target.value) //this is the one im concerned about
this.setState({ value: e.target.value, hasError: false, errorMsg: this.state.errorMsgSafe });
if (this.props.validateOn && (this.props.validateOn === undefined || this.props.validateOn === "onChange")) {
this.validaciones();
};
};
该函数partialSearch 只会在值长度大于 3 时触发,但我想添加另一个条件,并且只有在过去 300 毫秒内值没有改变时才会触发它。
我该怎么做呢?
编辑:我尝试添加一个去抖动/油门,但它似乎根本不起作用,该功能永远不会触发
这是我的全部代码
async partialSearch(searchTerm?: string) {
const environment = process.env.REACT_APP_ENV ? process.env.REACT_APP_ENV : "pre";
const api = process.env.REACT_APP_API ? process.env.REACT_APP_API : "my_api";
const api_version = "v2";
let baseUrl = getBaseUrl(api, environment) + "/search?q=" + searchTerm
return fetchSPA(baseUrl, undefined, { version: api_version })
.then(res => {
if (res && res.data && res.data.length) {
const firstFive = res.data[0].resultSearch?.cars.slice(0, 5).map(val => {
return { denominacion: val.denominacion, plate: val.id };
})
if (firstFive !== undefined) this.setState({ autocompleteValues: firstFive })
}
}).catch((res) => {
console.log("Error Fetch:: ", res)
});
}
onChange = e => {
this.setState({
autocompleteValues: [],
showPredictivo: true
})
if (e.target.value.length > 3) _.debounce(() => this.partialSearch(e.target.value), 300)
this.setState({ value: e.target.value, hasError: false, errorMsg: this.state.errorMsgSafe });
if (this.props.validateOn && (this.props.validateOn === undefined || this.props.validateOn === "onChange")) {
this.validaciones();
};
};
调用它的组件
没有去抖动/节流它可以工作,但是添加它时,它永远不会触发
<SCInput
type={type || "text"}
id={id ? id : null}
name={name}
disabled={disabled}
readOnly={readOnly}
style={style}
hasError={errorMsg ? true : false}
compact={compact}
onChange={onChange}
onBlur={onBlur}
placeholder={placeholder}
value={this.state.value}
>
【问题讨论】:
-
去抖呢?
-
@Roy.B 我试图实现它,但到目前为止崩溃``` if (e.target.value.length > 3) _.debounce(this.partialSearch(e.target.value) , 300)``` Debounce 需要一个函数
-
@mouchin777 尝试使用
() => this.partialSearch(e.target.value)作为debounce的第一个参数,它将partialSearch调用包装在一个函数中。否则,您将传递partialSearch的输出而不是函数。
标签: reactjs