reactjs - 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
解决方案
[]
用作您的效果依赖项参数,以便它仅在您的组件安装和卸载时运行。使用设置状态的回调方法,使其始终使用最新版本,count
而不是将其用作依赖项。
useEffect(() => {
const handleKeyUp = (e) => {
if (e.keyCode === 13) {
setCount(prevCount => prevCount + 1);
}
}
window.document.addEventListener('keyup', handleKeyUp);
return () => {
window.document.removeEventListener('keyup', handleKeyUp);
}
}, []);
推荐阅读
- r - 如何检测另一个字符串向量中的多个字符串
- php - curl_getinfo() 显示执行前后的空参数
- angular - *ngFor 在 Angular 6 中使用 jsPDF 时不显示数据
- python - Python比较两个特定的字典
- reactjs - 如何在子组件的构造函数中等待父组件的props
- scala - 将 Twitter Future[False] 转换为特殊 Future 的惯用方式?
- google-cloud-composer - 如何在 GoogleCloudComposer 中使用 KubernetesPodOperator 运行具有特权标志的容器?
- json - 如何将json批量转换为csv?
- excel - Excel - 将值与对应列匹配,检查值并删除行
- javascript - 跳房子关闭模式 onNext 或 onEnd