我有一个可以通过两种方式触发的搜索组件。一种由用户键入(去抖动),另一种由按钮重试。react-hooks/exhaustive-deps
的建议实际上给我带来了一个错误,因为当我只想要第一个触发时,观看searchTerm
会触发两种效果。我应该采取另一种方法吗?
export default function Search(props) {
const [searchTerm, setSearchTerm] = useState('')
const [retryCounter, setRetryCounter] = useRetryCounter() // number (int) of manual retries
function search() { ... }
const debouncedSearch = useRef(lodash.debounce(search, 300, { maxWait: 500 })).current
useEffect(() => {
debouncedSearch(searchTerm)
}, [searchTerm, debouncedSearch])
// when `searchTerm` changes, a user has typed into an <input />, so do a debounced search
useEffect(() => {
// i want to continue using the `searchTerm` provided by the user preivously
search(searchTerm)
}, [retryCounter])
// if i add `searchTerm` as a dep, then BOTH useEffects fire, and `search` gets fired twice.
// therefore, i explicitly want to ignore changes to `searchTerm` here
...
return (
<>
<input value={searchTerm} onChange={e => setSearchTerm(e.target.value)} />
<button onClick={setRetryCounter}>retry</button>
</>
)
}
我还注意到在该规则的官方讨论中,@StevenMyers32 的问题没有得到解决(他有一个代码框示例),他的示例似乎是“如果我包含此依赖项,useEffect 将错误地触发”的类似问题。