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

124
Views
¿Cómo puedo actualizar el estado como una matriz de objetos sin anular el estado anterior?

Quiero actualizar setTopic sin anular el estado anterior. Pero estoy recibiendo el topic is not iterable .

¿Qué probé? Intenté buscar ejemplos diferentes en el desbordamiento de la pila, pero aún no pude descubrir cómo agregar el estado actualizado sin perder el estado anterior.

Además, ¿cuál es una mejor manera de guardar múltiples temas: una matriz de objetos, simplemente objetos o simplemente una matriz?

 const AddTopic = (props) => { const { subjectName } = props; const [topic, setTopic] = useState([ { topics: [ { id: Math.random().toString(36).substr(2, 7), topicName: "topic name", subject: subjectName, }, ], }, ]); const addTopicHandler = () => { setTopic( [...topic].map((item) => { return { ...item, id: Math.random().toString(36).substr(2, 7), topicName: "another topic name", subject: subjectName, }; }) ); }; console.log(topic);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  1. En lugar de que el componente secundario use el estado, eleve el estado a un componente principal y luego simplemente cree componentes de Topic tontos a partir del estado.

  2. Cambia el nombre de tu estado. Llámalo topics , y la función de actualización setTopics . Inicialícelo como una matriz, no una matriz que contenga un objeto que contenga una matriz.

  3. No puede registrar inmediatamente un estado actualizado. Debe usar useEffect para observar los cambios en el estado y luego registrar algo.

 const { useEffect, useState } = React; // Topic component - just gets handed the // subject (in this example) in the props function Topic({ subject, category }) { return <div>{subject}: {category}</div>; } function Example() { // Initialise `topics` as an array const [ topics, setTopics ] = useState([]); // When `topics` is updated, log the updated state useEffect(() => console.log(JSON.stringify(topics)), [topics]); // Helper function that maps over the state and // produces an array of topics function getTopics() { return topics.map(topic => { const { subject, category } = topic; return ( <Topic subject={subject} category={category} /> ); }); } // Helper function to add a new topic object // to the topics state function addTopic() { const obj = { subject: 'Math', category: 'Fish' }; setTopics([...topics, obj ]); } return ( <div> <div>{getTopics()}</div> <button onClick={addTopic}>Add topic</button> </div> ); }; ReactDOM.render( <Example />, document.getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

about 4 years ago · Juan Pablo Isaza Report

0

Intenta reemplazar [...topic].map con [...topic.topics].map .

editar Lo siento, no vi que el topic en sí es un arreglo de objs, por lo que debería ser: [...topic[0].topics].map .

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!