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

192
Views
¿Cómo actualizar y apuntar al índice correcto en una matriz que está anidada en un objeto?

Tengo el siguiente estado de reacción, quiero actualizar el segundo valor, no el objeto completo y tampoco quiero usar un objeto como valor, por ahora solo puedo cambiar el objeto completo pero no el valor deseado específico cómo target y actualice el índice deseado.

 // State const [state, setState] = useState({ element: [false, 'starter text'] }); // Update State logic setState({ ...state, element: [(element[1] = 'updated text')] });

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Al actualizar el estado en React, copia superficialmente el estado y el estado anidado que está actualizando. Para matrices, esto significa que copia superficialmente la matriz.

 // State const [state, setState] = useState({ element: [false, 'starter text'] }); // Update State logic setState(state => ({ // shallow copy any previous root-level state ...state, // shallow copy the previous state's element array // when the mapped index matches the index you want to update // return the updated value, otherwise return existing value element: state.element.map((el, i) => i === 1 ? 'updated text' : el) }));

Si la matriz era una matriz de objetos, también debe copiarlos superficialmente y luego actualizar la propiedad anidada.

Ejemplo:

 element: state.element.map( (el, i) => i === 1 ? { ...el, nestedProperty: 'updated text' } : el )

Sé que este documento de patrones de actualización inmutable es de Redux, pero resuelve muchos problemas comunes de actualización de estado de React.

about 4 years ago · Juan Pablo Isaza Report

0

Puede crear un nuevo estado de estado como codeSandbox

 setState(oldState => { const newState = { ...oldState, element: [ ...oldState.element ]}; newState.element[1] = "updated text"; return newState; })
about 4 years ago · Juan Pablo Isaza Report

0

Puedes usar Object.assign . Dado que una matriz es un Objeto con índices como sus propiedades, puede hacer esto:

 const arr = [1, 2, 3, 4, 5]; const updatedArr = Object.assign([], arr, { 1: 10 }); // Update value at index 1. console.log(arr); console.log(updatedArr);

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!