javascript - 在每个渲染上重新添加 React hooks 事件侦听器(exhaustive-deps 错误)
问题描述
我将一个函数作为道具传递并调用它useEffect
来触发重新渲染,然后在每个渲染上重新添加一个新的事件侦听器。
如果我incrementCount
从依赖项列表中删除并将其保留为空数组[]
,则会收到react-hooks/exhaustive-deps
linting 错误,但是,它不会在初始渲染后触发。
function useApp({ incrementCount, count }) {
console.log(count);
// this gets triggered on every render
useEffect(() => {
console.log('add event listener');
window.addEventListener('click', incrementCount);
return () => {
window.removeEventListener('click', incrementCount);
};
}, [incrementCount]);
}
function App() {
const [count, setCount] = useState(0);
function incrementCount() {
console.log('increment');
setCount(prevCount => prevCount + 1);
}
useApp({ incrementCount, count });
return <div>click</div>;
}
解决方案
我认为你可以使用useCallback
反应钩子中的 api
https://reactjs.org/docs/hooks-reference.html#usecallback
function App() {
const [count, setCount] = useState(0);
const incrementCount = useCallback(() => {
console.log('increment');
setCount(prevCount => prevCount + 1);
}, [])
useApp({ incrementCount, count });
return <div>click</div>;
}
推荐阅读
- angular - 如何在 Angular 中为 Clarity Datepicker 设置默认值
- java - Cassandra:对现有表执行转换的策略
- python - 使用 Python 列出 linux 中的所有守护进程/服务名称?
- trello - Trello 开机显示多个卡片徽章
- java - 将 vensim 集成到 anylogic 中但出现运算符错误
- node.js - 更改 package.json 时“npm install”和“npm update”的行为是什么?
- oracle - oracle 表单获取表和多行块中的数据
- php - 为什么我的 PHP 会话变量只能在特定浏览器中工作而在其他浏览器中失败?
- php - 在 Symfony 4.2 中通过 Linkedin 登录
- sql - 查询以返回连续 X 天内值的最低 SUM