在每次渲染时重新添加 React hooks 事件侦听器(exhaustive-deps 错误)
React hooks event listener re-added on each render (exhaustive-deps error)
我将一个函数作为 prop 传递并在 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>;
}
我认为你可以使用 React Hooks 中的 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>;
}
我将一个函数作为 prop 传递并在 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>;
}
我认为你可以使用 React Hooks 中的 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>;
}