Creé una entrada, cuando escribes algo y haces clic en el botón, se agrega valor a nuestro estado, ahora estoy tratando de actualizar la opción de selección del estado de esta manera:
const NewGroup = () => { const [group, setGroup] = useState([]); const addToGroup = (e) => { const newGroup = group; newGroup.push(e.target.previousElementSibling.value); setGroup(newGroup); }; return ( <div> <input type="text" name="" id="" /> <button onClick={addToGroup}>submit</button> <div> <select name="" id=""> {group.map((category) => { return <option value=''>{category}</option>; })} </select> </div> </div> ); }; export default NewGroup;Pero no pasó nada.
Puede introducir otro useState() para escribir en el elemento <input> . Y cuando se presiona el botón Enviar, solo empujas someText a la matriz de group .
const NewGroup = () => { const [group, setGroup] = useState([]); const [someText, setSomeText] = useState(""); const addToGroup = (e) => { // Takes up all the present elements(of array group) and adds new element (search) let temp = [...group, someText]; setGroup(temp); }; return ( <div> <input type="text" name="" id="" value={someText} onChange={(e) => { setSomeText(e.target.value); }} /> <button onClick={addToGroup}>submit</button> <div> <select name="" id=""> {group.map((category, index) => { return ( <option key={index} value=""> {category} </option> ); })} </select> </div> </div> ); } export default NewGroup;Aquí está el enlace a la aplicación de trabajohttps://codesandbox.io/s/boring-ptolemy-0cwzmi?file=/src/App.js
Primero, no debería obtener el valor de su entrada usando el DOM directamente, sino que debería usar una Ref.
En segundo lugar, el problema es que está mutando el valor del grupo directamente en lugar de copiarlo. Cuando llamas a setGroup, React no se da cuenta de que hubo ningún cambio (porque el valor anterior es igual al valor actual). En su lugar, desea copiar la matriz y agregar su nuevo elemento:
// Previously: const newGroup = group; const newGroup = [...group];Eso debería ser todo lo que tienes que hacer para que tu código funcione. Sin embargo, lo simplifiqué y lo limpié un poco más con los comentarios en línea a continuación.
const NewGroup = () => { // Here's where our input will be stored so we can use it later (instead of querying the dom directly) const inputRef = React.useRef(); const [group, setGroup] = React.useState([]); // Use React.useCallback so the function doesn't change on every render const addToGroup = React.useCallback((e) => { // We call setGroup with a function that returns the new group value. The first argument is the current group value. We return a new array by spreading the existing value and adding our new value setGroup((v) => [...v, inputRef.current.value]); }, []); return ( <div> <input type="text" ref={inputRef} name="" id="" /> <button onClick={addToGroup}>submit</button> <div> <select name="" id=""> {group.map((category) => { return ( <option value="" key={category}> {category} </option> ); })} </select> </div> </div> ); };