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} />} </> ); } }
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中文網其他相關文章!