我有一个可以通过两种方式触发的搜索组件。一种是由用户键入(反跳),另一种是通过按钮重试。 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>
</>
)
}
我还注意到了on the official discussion of this rule that @StevenMyers32's question was not addressed(他有一个codesandbox示例),他的示例似乎是一个类似的问题,即“如果我包括此依赖项,useEffect将错误触发”。