React 的流行归功于其基于组件的架构。通常,我们有一些组件可以监听输入更改并触发 API 调用来检索数据。我们希望对这些 API 调用进行反跳以避免发出不必要的请求。
import React, { useState, useEffect, Suspense } from 'react'; const debounce = (fn, delay) => { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { fn(...args); }, delay); }; }; const SearchBox = () => { const [inputText, setInputText] = useState(''); const [searchResults, setSearchResults] = useState(null); const fetchResults = async (text) => { const response = await fetch(`/search?text=${text}`); const data = await response.json(); setSearchResults(data); }; const debouncedFetchResults = debounce(fetchResults, 500); useEffect(() => { if (!inputText) { return; } debouncedFetchResults(inputText); }, [inputText, debouncedFetchResults]); return ( <> <input type="search" value={inputText} onChange={(e) => setInputText(e.target.value)} /> <Suspense fallback={<div>Loading...</div>}> {searchResults && <Results results={searchResults} />} </Suspense> </> ); };
在此示例中,我们使用 debounce 函数来包装 fetchResults 函数,并且仅在 500 毫秒不活动后进行 API 调用。我们在 inputText 状态的每次变化时对函数进行去抖处理。然后,我们在获取结果时使用 Suspense 渲染占位符。
尽管鼓励使用 React hook,但您也可以使用类组件来进行反跳:
import React, { Component } from 'react'; const debounce = (fn, delay) => { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { fn(...args); }, delay); }; }; class SearchBox extends Component { constructor(props) { super(props); this.state = { inputText: '', searchResults: null }; this.debouncedFetchResults = debounce(this.fetchResults, 500); } fetchResults = async (text) => { const response = await fetch(`/search?text=${text}`); const data = await response.json(); this.setState({ searchResults: data }); }; handleInputChange = (e) => { const text = e.target.value; this.setState({ inputText: text }); this.debouncedFetchResults(text); }; render() { return ( <> <input type="search" value={this.state.inputText} onChange={this.handleInputChange} /> {this.state.searchResults && <Results results={this.state.searchResults} />} </> ); } }
在 React 中附加事件处理程序时,请记住事件对象被池化以减少GC压力。如果您想与处理程序调用异步访问事件属性,可以使用 e.persist() 方法来防止事件返回到池中:
const onClick = (e) => { e.persist(); // Prevent the event object from being returned to the pool setTimeout(() => { // Access event properties here }, 0); }; <button onClick={onClick}>Click Me</button>
以上是如何在 React 应用程序中实现去抖?的详细内容。更多信息请关注PHP中文网其他相关文章!