Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
Actualice el estado dinámicamente con niveles anidados de objetos y matriz

Este es el problema

Estoy tratando de actualizar el estado de este objeto llamado singleCarers

Tengo el índice de la lista en la matriz de listas que necesito actualizar

pero The key Monday: necesita ser dinámico & the key start: & finish: también necesita ser dinámico

 const indexOfRoster = index; const dayOfRoster = day; const { value, name } = e.target; // name represents either start: or finish: & value is the value of start or finish eg. name:value === start: "09:10"
 { "rosters": [ { "schedule": { "monday": { "start": "", "finish": "", }, }, }, ] }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Tienes dos problemas:

  1. Necesita hacer referencia al objeto usando nombres de propiedades computadas
  2. el uso de una devolución de llamada en el estado establecido requiere que devuelva un nuevo estado de la función.
 setSingleCarers((prevState) => { const updatedRosters = prevState.rosters.map((roster, index) => ( index === indexOfRoster ? { // update the target roster ...roster, schedule: { ...roster.schedule, [dayOfRoster]: { ...roster.schedule[dayOfRoster], [name]: value, }, }, } : roster, )); return { // return the new State ...prevState, rosters: updatedRosters, }; }

esto puede parecer excesivo, en cuyo caso puede buscar soluciones como immer u otras bibliotecas que facilitan este tipo de manipulación de objetos en lugar de tener que recordar hacer una copia profunda de objetos

about 4 years ago · Juan Pablo Isaza Report

0

No lo pienses más, si no usas tipos de datos complejos esta es la mejor opción

JSON.parse(JSON.stringify(object))

 const auxState = JSON.parse (JSON.stringify(reactState)) // now modify auxState auxState[index][day]={ start:"val", end:"val" } setReactState(auxState)

Si quieres ponerte elegante

 function clone(obj) { if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj) return obj; if (obj instanceof Date) var temp = new obj.constructor(); //or new Date(obj); else var temp = obj.constructor(); for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { obj['isActiveClone'] = null; temp[key] = clone(obj[key]); delete obj['isActiveClone']; } } return temp; } const auxState = clone(reactState) // Modify auxState setReactState (auxState)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!