gpt4 book ai didi

javascript - 在每次渲染时重新添加 React hooks 事件监听器(exhaustive-deps 错误)

转载 作者:行者123 更新时间:2023-11-30 13:59:52 25 4
gpt4 key购买 nike

我将一个函数作为 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>;
}

关于javascript - 在每次渲染时重新添加 React hooks 事件监听器(exhaustive-deps 错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56491916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com