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

237
Views
¿Cómo empujar un objeto dentro de una matriz anidada usando React y TypeScript?

¿Cuál es la forma correcta, usando TypeScript y React, para crear una función que inserte un nuevo objeto dentro de los items de la matriz?

 const [state, setState] = useState([ { firstname: "William", items: [ { name: "sword", damage: 100 }, { name: "shield", damage: 50 }, ], }, { firstname: "Allison", items: [ { name: "bow", damage: 70 }, { name: "axe", damage: 120 }, ], }, ]); const addNewItem = (newItem: object, CharacterIndex: number) => { // Push new item inside character's items. setState(newState) }; return ( <button onClick={() => addNewItem({ name: "dagger", damage: 50 }, 2)}> Add Item </button> );

Ya lo hice una vez usando JavaScript, pero con Typescript a menudo obtengo algunos errores.

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

0

Puede implementarlo de la manera que mejor le parezca.

 const addNewItem = (newItem: object, CharacterIndex: number) => { //I would use this setState(state.map((elem: object, index: number) => { return index === characterIndex ? { ...elem, items: [ ...elem.items, newItem ] } : elem; })); };
about 4 years ago · Juan Pablo Isaza Report

0

Debe escribir su estado y todas sus matrices

 import { useState } from "react"; import "./styles.css"; const INITIAL_STATE = [ { firstname: "William", items: [ { name: "sword", damage: 100 }, { name: "shield", damage: 50 } ] }, { firstname: "Allison", items: [ { name: "bow", damage: 70 }, { name: "axe", damage: 120 } ] } ]; type Item = { name: string; damage: number; }; type StateParams = { firstname: string; items: Item[]; }; export default function App() { const [state, setState] = useState<StateParams[]>(INITIAL_STATE); const addNewItem = (newItem: Item, characterIndex: number) => { const nextState = state.map((st, i) => { if (i === characterIndex) { return { firstname: st.firstname, items: [...st.items, newItem] }; } else { return st; } }); setState(nextState); console.log(state); }; return ( <button onClick={() => addNewItem({ name: "dagger", damage: 50 }, 1)}> Add Item </button> ); }

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!