【问题标题】:React. Trigger a function inside an onChange only if N time has passed without onChange做出反应。仅当 N 时间过去而没有 onChange 时才在 onChange 内触发函数
【发布时间】: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 尝试使用() =&gt; this.partialSearch(e.target.value) 作为debounce 的第一个参数,它将partialSearch 调用包装在一个函数中。否则,您将传递 partialSearch 的输出而不是函数。

标签: reactjs


【解决方案1】:

您很可能在此处寻找去抖动/节流。 本文讲解场景:https://css-tricks.com/debouncing-throttling-explained-examples/

简而言之,通过去抖动,您将一个函数包装在经常调用的函数上。 “包装器”函数确保内部的函数只有在经过一定时间后才会再次被调用。

实现此功能的一种简单方法是使用 lodash 之类的实用程序库,或者您可以在 Google 上搜索合适的去抖动功能。

【讨论】:

    猜你喜欢
    • 2020-03-25
    • 2019-02-19
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多