Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
¿Cómo usar useState en addEventListener?

Si hago clic derecho en el DivElement rojo, quiero cambiar mi estado

Como el estado ha cambiado, pensé que podía ver console.log

Pero no funciona

Aquí está mi código

 import { useState, useRef, useEffect } from "react"; function Main() { const [testState, setTestState] = useState(0); const testRef = useRef(null); function clickHandler(event) { setTestState(testState + 1); } useEffect(() => { if (!testRef) return; testRef.current.addEventListener('contextmenu', (event) => { clickHandler(event) }); }, [testRef]); useEffect(() => { console.log('testState: ', testState); }, [testState]); return ( <div ref={testRef} style={{width: '100%', display: 'block', height: '32px', backgroundColor: 'red'}} /> ); } export default Main;
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

el problema surge cuando hace referencia a su estado, tenga en cuenta que setState se ejecuta de forma asincrónica (piense en set state como una solicitud para volver a procesar el componente).

cambiando su setTestState(testState + 1); setTestState((oldVal) => oldVal + 1); tu ejemplo funcionará. echa un vistazo a este ejemplo de stackblitz

Saludos,

about 4 years ago · Juan Pablo Isaza Report

0

Debe usar una cleanup function y preventDefault en clickHandler.

 import { useState, useRef, useEffect, useCallback } from "react"; function Main() { const [testState, setTestState] = useState(0); const testRef = useRef(null); const clickHandler = useCallback((event) => { event.preventDefault(); setTestState((test) => test + 1); }, []); useEffect(() => { const refElement = testRef.current; refElement.addEventListener("contextmenu", clickHandler); return () => refElement.removeEventListener("contextmenu", clickHandler); //cleanup function }, [clickHandler]); useEffect(() => { console.log("testState: ", testState); }, [testState]); return ( <div ref={testRef} style={{ width: "100%", display: "block", height: "32px", backgroundColor: "red" }} /> ); } export default Main;

Códigos de trabajoandbox

about 4 years ago · Juan Pablo Isaza Report

0

Aquí hay un fragmento de código de trabajo:

 function Main() { const [testState, setTestState] = useState(0); const testRef = useRef(null); useEffect(() => { function clickHandler(event) { setTestState((old) => old + 1); } if (!testRef) return; const ref = testRef.current; ref.addEventListener("contextmenu", clickHandler); return () => ref.removeEventListener("contextmenu", clickHandler); }, [testRef, testState]); useEffect(() => { console.log("testState: ", testState); }, [testState]); return ( <div ref={testRef} style={{ width: "100%", display: "block", height: "32px", backgroundColor: "red", }} /> ); }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!