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

132
Vistas
Agregar datos a una matriz existente de objetos a través de un controlador onChange

Tengo una variedad de objetos.

 [ { "0": { "title": "Jessica Simpson", "id": "324352342323432", "url": "image-url.jpg", "colourScheme": "", "type": "", "enabledUnits": "" }, "1": { "title": "Bill Murray", "id": "5qocDvdm9XETFz33p725IG", "url": "image-url.jpg", "colourScheme": "", "type": "", "enabledUnits": "" }, } ]

Estoy intentando agregar actualizar el valor de colourScheme dentro del objeto a través de un controlador de eventos onChange.

OnChangeHandler

 const createOnChangeHandler = (floorPlan: FloorPlan, property: 'colourScheme' | 'type') => ( e: React.ChangeEvent<HTMLInputElement> ) => { console.log(( e.target.value )) const itemList = floorPlans.concat(); const index = itemList.findIndex((i) => i.id === floorPlan.id); itemList.splice(index, 1, {...floorPlans, [property]: e.target.value}); };

Pero se está agregando fuera del objeto. Por ejemplo... observe "colourScheme": "Black" está afuera.

 { "0": { "title": "Angeline Espaze", "id": "5qocDvdm9XETFz33p725IG", "url": "image-url.jpg", "colourScheme": "", "type": "", "enabledUnits": "" }, "colourScheme": "Black" } ]

donde me gustaría

 [ { "0": { "title": "Angeline Espaze", "id": "5qocDvdm9XETFz33p725IG", "url": "image-url.jpg", "colourScheme": "Black", "type": "", "enabledUnits": "" }, } ] I think the issue is with itemList.splice? inside the onChange
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

El problema es:

  1. Estás esparciendo algo incorrecto en el nuevo objeto, y

  2. No estás llamando a un creador de estado.

No usaría splice para esto en absoluto, puede hacer la actualización del objeto mientras copia la matriz en lugar de hacerlo después. En cambio (ver comentarios):

 const createOnChangeHandler = (floorPlan: FloorPlan, property: 'colourScheme' | 'type') => ( e: React.ChangeEvent<HTMLInputElement> ) => { const {value} = e.target; // Call the state setter; because we're updating state based on existing state, it's // best to use the callback version setFloorPlans(floorPlans => { // Return a new array with a replaced object return floorPlans.map(entry => { if (entry.id === floorPlan.id) { // Create a replacement object return {...entry, [property]: value}; } return entry; // No change to this object }); }); };

Eso es asumiendo que estás usando ganchos. Si está usando un componente de clase, use this.setState en su lugar:

 const createOnChangeHandler = (floorPlan: FloorPlan, property: 'colourScheme' | 'type') => ( e: React.ChangeEvent<HTMLInputElement> ) => { const {value} = e.target; // Call the state setter; because we're updating state based on existing state, it's // best to use the callback version this.setState(({floorPlans}) => { // Return a new array with a replaced object return {floorPlans: floorPlans.map(entry => { if (entry.id === floorPlan.id) { // Create a replacement object return {...entry, [property]: value}; } return entry; // No change to this object }}); }); };
about 4 years ago · Juan Pablo Isaza Denunciar

0

Pruebe el siguiente código.

 const createOnChangeHandler = (floorPlan: FloorPlan, property: 'colourScheme' | 'type') => ( e: React.ChangeEvent<HTMLInputElement>) => { let lclfloorPlans = [...floorPlans]; lclfloorPlans.forEach(item => { for (var key in item) { if (item[key].id === floorPlan.id) { item[key][property] = e.target.value; break; } } }); setFloorPlans(lclfloorPlans); // assign to your state value };
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