简体   繁体   中英

React useEffect hook event listener fired twice

I have this hook:

useEffect(() => {
        window.addEventListener('keydown', handleKeyPress);
        return () => window.removeEventListener('keydown', handleKeyPress);
        }, [props.tps])

For some reason, though, on the associated key press, the handleKeyPress function is called twice. I tried adding handleKeyPress as a dependency and that does not work, either. Any ideas?

I saw this late but for others who may have this problem: it is probably because of React.StrictMode inside index.js and it is an intentional thing when using hooks. here is the reference

I am not sure why you added props.tps , but try to remove it from dependency arrays.

props.tps is not doing anything there, you need to delete the props.tps from the dependency array because:

1.- The event listener (as it's not from the component itself but from window ) should be created on the "componentDidMount" or what's equivalent an empty dependency array.

2.- The values on the dependency array should be also inside the useEffect function to make it work properly.

Try taking it out the dependency array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM