Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
¿Cómo manejar elementos anidados en ganchos?
const [mealData, setMealData] = useState({ title: '', description: '', category: '', price: '', mealIMG: null, ingredients: [], })

Así que tengo este objeto de estado en mi componente. Cuando hago clic en el botón Agregar, el estado se vuelve así: (digamos que hicimos clic dos veces)

 { title: '', description: '', category: '', price: '', mealIMG: null, ingredients: [ {ingredient:"", qty:"", unit:"", id:id}, {ingredient:"", qty:"", unit:"", id:id}, ], }

Ahora, en el controlador de eventos de cambio, quiero actualizar el estado sin mutar el otro. Estoy usando esta función para lograr el trabajo, pero no funciona:

 const handleIngredients = (e, index) => { const { name } = e.target setMealData((prev) => { return { ...prev, ingredients: [ { ...prev.ingredients[index], [name]: e.target.value, }, ], } }) }

¿Alguna pista, por favor?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

 const { useEffect, useState } = React; function Example() { const [ state, setState ] = useState({ title: '', description: '', category: '', price: '', mealIMG: null, ingredients: [] }); useEffect(() => { const json = JSON.stringify(state.ingredients); console.log(json); }, [state]); function handleChange(e) { // Grab our needed props from the // changed input const { name, value, parentNode: { id }, } = e.target; // Get ingredients from state const { ingredients } = state; // Is there is an object in the ingredients // where the id matches the id from the props const found = ingredients.find(i => { return i.id === id; }); // If there is... if (found) { // Create a new object using the found // object, and the name/value of the input const updated = { ...found, [name]: value }; // `filter` out all the objects where the object id // doesn't match the id from props const filtered = ingredients.filter(i => { return i.id !== id }); // Set the new state using the filtered // array, and the updated object setState({ ...state, ingredients: [ ...filtered, updated ] }); // If an object isn't found } else { // Add a new object to the ingredients array setState({ ...state, ingredients: [ ...state.ingredients, { id, [name]: e.target.value } ] }); } } return ( <div> <Input id="1" handleChange={handleChange} /> <Input id="2" handleChange={handleChange} /> </div> ); }; function Input({ id, handleChange }) { return ( <div className="set" id={id} onChange={handleChange}> Ingredient: <input name="ingredient" /> Qty: <input name="qty" /> Unit: <input name="unit" /> </div> ); } ReactDOM.render( <Example />, document.getElementById('react') );
 input { display: block; } .set { display: inline-block; margin-bottom: 1em; border: 1px solid #454545; padding: 0.2em; width: 45%; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda