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);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.
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.
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>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 .