首页 > 解决方案 > How do you add an keyup event listener to window in a React functional component that only gets added when the app originally loads?

问题描述

First off, here's my code:

import React, {useState, useEffect} from 'react';

function App() {

  const [count, setCount] = useState(0);

  useEffect(() => {
    const handleKeyUp = (e) => {
      if (e.keyCode === 13) {
        setCount(count + 1);
      }
    }
    window.document.addEventListener('keyup', handleKeyUp);
    console.log('event listener created.');
    return () => {
      window.document.removeEventListener('keyup', handleKeyUp);
      console.log('event listener removed.');
    }
  }, [count, setCount]);

  return (
    <output>Count: {count}</output>
  );
}

export default App;

A working copy is at https://codesandbox.io/s/stoic-curie-rl0qe.

This code works: pressing Enter increments count. The concern I have is that the listener gets added and removed every time the Enter key is pressed. You can see this in the console. I would like the event listener to be added when the React component initially mounts, and to keep listening until the component unmounts. How would I do that?

EDIT

As per the accepted solution, here is the working code:

import React, {useState, useEffect} from 'react';

function App() {

  const [count, setCount] = useState(0);

  useEffect(() => {
    const handleKeyUp = (e) => {
      if (e.keyCode === 13) {
        setCount(prevCount => prevCount + 1);
      }
    }
    window.document.addEventListener('keyup', handleKeyUp);
    console.log('event listener created.');
    return () => {
      window.document.removeEventListener('keyup', handleKeyUp);
      console.log('event listener removed.');
    }
  }, []);

  return (
    <output>Count: {count}</output>
  );
}

export default App;

Working copy at https://codesandbox.io/s/react-add-keyup-event-on-win-g23cg

标签: reactjs

解决方案


[]用作您的效果依赖项参数,以便它仅在您的组件安装和卸载时运行。使用设置状态的回调方法,使其始终使用最新版本,count而不是将其用作依赖项。

useEffect(() => {
  const handleKeyUp = (e) => {
    if (e.keyCode === 13) {
      setCount(prevCount => prevCount + 1);
    } 
  }

  window.document.addEventListener('keyup', handleKeyUp);

  return () => {
    window.document.removeEventListener('keyup', handleKeyUp);
  }
}, []);

推荐阅读