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

150
Views
Actualizar un valor de objeto en una matriz anidada Reaccionar

Estoy tratando de actualizar un valor dentro del objeto de estado de una aplicación React. Puedo cambiar la cadena de estado, pero parece que no puedo averiguar cómo acceder a la tecla hp para cada luchador. He intentado diferentes formas (he escrito 2 en este ejemplo) sin ningún éxito. ¿Cuál es la forma correcta de acceder a la clave de cada luchador cuando tienes una matriz con objetos anidados?

 export default class App extends Component { state = { status: 'Fighters are Ready...', fighters: [ { name: 'Fighter 1', hp: 150, image: '' }, { name: 'Fighter 2', hp: 150, image: '' } ] } handleClick = (e) => { // console.log(e) if (e.target.name === 'Fighter 1') { this.setState({ hp : this.state.fighters[1].hp - 10, status: e.target.name + ' is attacking ' + this.state.fighters[1].name }) } else { this.setState({ [Object.keys(this.state.fighters)[0].hp] : this.state.fighters[0].hp - 10, status: e.target.name + ' is attacking ' + this.state.fighters[0].name }) } }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Debe asegurarse de devolver un objeto de la misma forma que el estado original, al mismo tiempo que evita la mutación. Aquí extendiendo el estado actual en un nuevo objeto, actualizando la cadena de status como estabas y luego usando una llamada map() para iterar sobre la matriz de fighters y actualizar el luchador que coincide con event.target .

 handleClick = (e) => { // console.log(e) this.setState({ ...this.state, status: e.target.name + ' is attacking ' + this.state.fighters.find(f => f.name !== e.target.name)?.name, fighters: this.state.fighters.map(fighter => fighter.name !== e.target.name ? ({ ...fighter, hp: fighter.hp - 10 }) : fighter) }) }
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!