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

137
Views
Mis funciones no siguen la sincronía usando React

No sé por qué la función handleSum no suma el valor actualizado proveniente de handleInput cuando invoco la función handleAll a través del evento de entrada onChange . Parece que suma con el valor anterior. ¿Puedes traer algo de luz aquí? ¡Gracias!

Aquí la parte JS:

 const card = () => { //hook defined const [input, setInput] = React.useState({ p1h1: "", p1h2: "", }); const [result, setResult] = React.useState("") //handle input change const handleInput = function(e){ setInput({ ...input, [e.target.name]: e.target.value }); }; //handle sum const handleSum = function(){ const { p1h1, p1h2 } = input; setResult(Number(p1h1) + Number(p1h2)); } //handle result player const handleAll = function (e) { handleInput(e) setTimeout (()=> {handleSum()},1000) // I inserted this setTimeout to double sure that this is executing after the previous function but didn't work. } }

Aquí la parte HTML:

 <input name= "p1h1" value={input.p1h1} onChange={handleAll} type= "number" min="0" </input> <input name= "p1h2" value={input.p1h2} onChange={handleAll} type= "number" min="0" </input> <h2>Result sum: {result}</h2>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

De acuerdo con las Reglas de los ganchos (ver mi comentario), no puede usar ganchos excepto en el nivel superior de los componentes funcionales . No anidado en otras funciones, no en if no en for , etc.

Por lo tanto, debe crear un componente funcional, como const Test = () => { return (<div />); }

Luego, debe llamar a su enlace y representar su HTML como JSX desde ese componente. Luego puede usar su función handleInput para actualizar el estado.

No necesita otro estado para mantener el resultado de la suma . Está bien calcular eso durante el renderizado.

Esto funcionará:

 const Test = () => { //hook defined const [input, setInput] = React.useState({ p1h1: '', p1h2: '', }); //handle input change const handleInput = function (e) { setInput({ ...input, [e.target.name]: e.target.value, }); }; const { p1h1, p1h2 } = input; const result = Number(p1h1) + Number(p1h2); return ( <div> <input name="p1h1" value={input.p1h1} onChange={handleInput} type="number" min="0"></input> <input name="p1h2" value={input.p1h2} onChange={handleInput} type="number" min="0"></input> <h2>Result sum: {result}</h2> </div> ); };
about 4 years ago · Juan Pablo Isaza Report

0

La forma en que llamas a handleSum no es correcta. Debe usar un useEffect para volver a representar el elemento cuando un estado particular cambia como una matriz de dependencias (segundo argumento de useEffect ). Puede obtener más información al respecto aquí https://reactjs.org/docs/hooks-effect.html .

 const App = () => { const [input, setInput] = React.useState({ p1h1: "", p1h2: "", }); React.useEffect(() => { handleSum() }, [input]) const [result, setResult] = React.useState("") //handle input change const handleInput = function(e){ setInput({ ...input, [e.target.name]: e.target.value }); }; //handle sum const handleSum = function(){ const { p1h1, p1h2 } = input; setResult(Number(p1h1) + Number(p1h2)); } return ( <div> <input name= "p1h1" value={input.p1h1} onChange={handleInput} type= "number" min="0"> </input> <input name= "p1h2" value={input.p1h2} onChange={handleInput} type= "number" min="0"> </input> <h2>Result sum: {result}</h2> </div>

) }

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!