Tengo una aplicación React donde quiero leer datos de un objeto en una matriz y luego renderizar esto. Sin embargo, se procesan duplicados de los mismos datos y, al investigar más, descubrí que la matriz a la que estoy empujando los elementos tiene una longitud de 8 o 12 (esto varía misteriosamente) en lugar de 4, que es la longitud que espero. ser - estar. La matriz tiene esta longitud incluso antes de enviarle elementos, como lo indica un registro de la consola justo después de la inicialización. Estoy completamente perplejo en cuanto a por qué sucede esto, ¿alguien puede ofrecer algunas ideas? ¡Gracias!
question_card.js
const arr = []; console.log(arr); const tempData = { id: 2, question_text: "When was the enigma code cracked?", answers: [ { answer_text: 1941 }, { answer_text: 1942 }, { answer_text: 1939 }, { answer_text: 1943 }, ], }; function getAnswers() { tempData.answers.forEach((answer) => { arr.push((<p>{answer.answer_text}</p>)); }); } function QuestionCard() { getAnswers(); return( <div> <p>This will be the question</p> <div>{arr}</div> </div> )}; export default QuestionCard;Aplicación.js
import "./App.css"; import QuestionCard from "./question_card"; function App() { return ( <div className="App"> <QuestionCard /> </div> ); } export default App;Salida: consola.log(arr)
question_card.js:3 [] 0: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 1: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 2: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 3: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 4: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 5: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 6: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 7: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 8: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 9: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 10: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} 11: {$$typeof: Symbol(react.element), type: 'p', key: null, ref: null, props: {…}, …} length: 12Como se menciona en los comentarios, está intentando llamar a la función getAnswers en cada nueva representación y eso estaba causando datos no deseados en la matriz tempData.answer .
Por lo tanto, no llame directamente a la función getAnswers en el componente QuestionCard . llámalo dentro de un gancho useEffect :
function QuestionCard() { useEffect(() => { getAnswers(); }, []) return( <div> <p>This will be the question</p> <div>{arr}</div> </div> )}; export default QuestionCard;