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>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> ); };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>) }