乐闻世界logo
搜索文章和话题

React 中如何实现 debounce 防抖函数?

3个答案

1
2
3

在React中实现防抖函数(debounce function)通常涉及到在组件中使用一个特定的函数,该函数能够延迟执行实际的处理逻辑,直到停止触发一段时间后。这样做可以减少像输入框连续输入这样的事件处理函数的调用次数,从而提高性能。

下面是在React组件中实现防抖功能的步骤:

  1. 创建防抖函数: 创建一个防抖函数,该函数会接收一个要延迟执行的函数 func 和延迟执行的时间 wait
javascript
const debounce = (func, wait) => { let timeout; return function executedFunction(...args) { const later = () => { clearTimeout(timeout); func(...args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; };
  1. 在React组件中使用防抖函数: 使用 useEffect 钩子配合防抖函数实现防抖效果。

假设我们有一个搜索输入框,我们想要在用户停止输入一段时间后再触发搜索,避免每次键入都进行搜索:

javascript
import React, { useState, useEffect } from 'react'; const SearchComponent = () => { const [inputValue, setInputValue] = useState(''); // 定义防抖函数 const debounceSearch = debounce((searchValue) => { console.log(`搜索: ${searchValue}`); // 在这里执行搜索逻辑,例如 API 调用 }, 500); useEffect(() => { if (inputValue) { debounceSearch(inputValue); } }, [inputValue]); return ( <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="输入关键词进行搜索" /> ); }; export default SearchComponent;

上面的例子中,我们在输入框的 onChange 事件中设置了 inputValue 的值,然后我们在 useEffect 中使用 inputValue 作为依赖项,这表示当 inputValue 改变时,useEffect 的回调会被执行。在 useEffect 的回调中,我们调用了 debounceSearch 函数,它会延迟执行搜索逻辑,直到用户停止输入500毫秒后。

这样,无论用户输入多快,真正的搜索逻辑只会在用户停止输入一段时间后才会执行,大大减少了不必要的处理和API调用。

2024年6月29日 12:07 回复

可以有一种使用React hooks 的简单方法。

第 1 步:定义一个状态来维护搜索到的文本

shell
const [searchTerm, setSearchTerm] = useState('')

步骤 2:使用 useEffect 捕获任何变化searchTerm

shell
useEffect(() => { const delayDebounceFn = setTimeout(() => { if (searchTerm) { // Write your logic here } }, 400) return () => clearTimeout(delayDebounceFn) }, [searchTerm])

第三步:编写一个函数来处理输入变化

shell
function handleInputChange(value) { if (value) { setSearchTerm(value) } }

2024年6月29日 12:07 回复

不受控制的组件

您可以使用该event.persist()方法

下面是使用Underscore.js '的示例_.debounce()

shell
var SearchBox = React.createClass({ componentWillMount: function () { this.delayedCallback = _.debounce(function (event) { // `event.target` is accessible now }, 1000); }, onChange: function (event) { event.persist(); this.delayedCallback(event); }, render: function () { return ( <input type="search" onChange={this.onChange} /> ); } });

请参阅这个 JSFiddle


受控组件

上面的例子显示了一个不受控制的组件。我一直使用受控元素,所以这是上面的另一个例子,但没有使用event.persist()“欺骗”。

JSFiddle也可用。不带下划线的示例

shell
var SearchBox = React.createClass({ getInitialState: function () { return { query: this.props.query }; }, componentWillMount: function () { this.handleSearchDebounced = _.debounce(function () { this.props.handleSearch.apply(this, [this.state.query]); }, 500); }, onChange: function (event) { this.setState({query: event.target.value}); this.handleSearchDebounced(); }, render: function () { return ( <input type="search" value={this.state.query} onChange={this.onChange} /> ); } }); var Search = React.createClass({ getInitialState: function () { return { result: this.props.query }; }, handleSearch: function (query) { this.setState({result: query}); }, render: function () { return ( <div id="search"> <SearchBox query={this.state.result} handleSearch={this.handleSearch} /> <p>You searched for: <strong>{this.state.result}</strong></p> </div> ); } }); React.render(<Search query="Initial query" />, document.body);
2024年6月29日 12:07 回复

你的答案