Estoy construyendo una gestión de formulario simple con un historial.
Repliqué una versión simple en codesandbox
import { useState } from "react"; import "./styles.css"; const sample = ["what", "who", "where"]; const sampleL = sample.length; export default function App() { const [, indexSet] = useState([0, 0]); const [, historySet] = useState([]); const onClickNext = () => { indexSet((index) => { const [i] = index; let x = i + 1; // for loop used for some checks but in sample only runs once for (; x < sampleL; x++) { console.log("next > index", { index, i, x }); historySet((history) => { const ex = [...history, i]; console.log("next > history", { h: history, i, ex }); return ex; }); return [x, 1]; } return index; }); }; const onClickBack = () => { historySet((history) => { console.log("back > history", { h: history }); if (history.length === 0) return history; const hx = [...history]; indexSet([hx.pop(), -1]); return hx; }); }; return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <p>Open console, click next twice, click back once</p> <p>Why is history with three values instead of two?</p> <button onClick={onClickNext}>Next</button> <button onClick={onClickBack}>Back</button> </div> ); }Mantuve el código lo más cerca posible de mi fuente original. Sin embargo, en mi computadora, las múltiples ejecuciones de indexSet se registran a través de la consola. En codesandbox, la matriz mágicamente tiene un elemento adicional. Ambos resultan con el mismo error.
¿Por qué indexSet se ejecuta dos veces, lo que hace que el historial se convierta en [0,1,1]? ¿Es esto un error con React?
Según React, su comportamiento esperado. https://github.com/facebook/react/issues/24057