在React中多次调用handleKeyPress方法

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  let [a, setA] = useState(0);
  let [b, setB] = useState(0);

  document.addEventListener("keyup", handleKeyPress);

  function handleKeyPress() {
    console.log("event occured!");
    setA(a + 1);
    setB(b + 1);
  }

  return (
    <div className="App">
      <h1>{a}</h1>
      <h2>{b}</h2>
    </div>
  );
}

I am setting the two states at a time in react. i read https://reactjs.org/docs/strict-mode.html and here. still not find what is wrong with my code. I have been trying to fix this issue for the past 24 hours using Google and asking friends for help. none of them worked. if you have any idea please guide me. thanks!

https://codesandbox.io/s/strange-rhodes-icwyx?file=/src/App.js

评论
  • 情侣
    情侣 回复

    您需要在组件的挂载上添加一次事件侦听器。

    当前,您在每个渲染上添加一个侦听器。

    export default function App() {
      const [a, setA] = useState(0);
      const [b, setB] = useState(0);
    
      useEffect(() => {
        function handleKeyPress() {
          console.log('event occured!');
          setA(p => p + 1);
          setB(b => b + 1);
        }
    
        document.addEventListener('keyup', handleKeyPress);
      }, []);
    
      return (
        <div className="App">
          <h1>{a}</h1>
          <h2>{b}</h2>
        </div>
      );
    }
    

    Edit dreamy-hugle-xqm37