问题描述
我有一个可以通过两种方式触发的搜索组件。一种是由用户键入(反跳),另一种是通过按钮重试。 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将错误触发”。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)