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
question from:
https://stackoverflow.com/questions/65855446/usestate-not-updating-on-javascript-event 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…