首页 > 解决方案 > 在每个渲染上重新添加 React hooks 事件侦听器(exhaustive-deps 错误)

问题描述

我将一个函数作为道具传递并调用它useEffect来触发重新渲染,然后在每个渲染上重新添加一个新的事件侦听器。

如果我incrementCount从依赖项列表中删除并将其保留为空数组[],则会收到react-hooks/exhaustive-depslinting 错误,但是,它不会在初始渲染后触发。

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>;
}

标签: javascriptreactjsreact-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>;
}

推荐阅读