Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm having trouble getting the "set" function of useState to work as I need. I would like to be able to use a keyboard listener to increment a counter, but even though the keyListener function is executing, selection doesn't grow past 1.

Is this an asynchronous updating issue?

To demonstrate my problem, I made the following glitch project. (To use, click on the yellow background and press keys to increment the selection counter.)

import React, { useState } from 'react';

function App() {
  const [selection, setSelection] = useState(0)
  
  const attachKeyListener = () => { 
    console.log("attaching listener")
    document.addEventListener("keydown", keyListener) 
  };
  
  const keyListener = (e) => {
    console.log("increasing selection")
    let tmp = selection + 1
    setSelection(tmp)
  };

  return (
    <div className="App" onClick={attachKeyListener} style={{background:"yellow"}}>
      Counter: {selection} 
    </div>
  );
}

export default App;

live example: https://gaudy-brave-tenor.glitch.me


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

You're currently attaching a new listener every time the div is clicked. Instead, add the listener just once, on initial mount, and use the callback form to ensure you have the up-to-date selection when setting anew:

function App() {
  const [selection, setSelection] = React.useState(0)
  React.useEffect(() => {
    console.log("attaching listener")
    const keyListener = (e) => {
      console.log("increasing selection")
      let tmp = selection + 1
      setSelection(selection => selection + 1)
    };
    document.addEventListener("keydown", keyListener) 
  }, []);
  
  return (
    <div className="App" style={{background:"yellow"}}>
      Counter: {selection} 
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...