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

162
Views
React State Hook inicializado a [] todavía muestra el tipo como indefinido

Código:

 const [input, setInput] = useState(''); const [studentList, setStudentList] = useState([]); useEffect(() => { console.log(studentList) console.log(studentList.type) }, [studentList]); return ( <div id="add-students-input-div"> <input type="text" id='add-students-input' value={input} placeholder='Enter a student to the database' onChange={(event) => { setInput(event.target.value) }} /> <div id="add-students-button" onClick={() => { setStudentList([document.getElementById('add-students-input').value, ...studentList]) setInput('') }}> <p>Add</p> </div> </div> )

Problema: la declaración de impresión para studentList devuelve la matriz, pero la declaración de impresión para studentList.type no está definida en todo momento, incluso después de agregar elementos a la matriz.

¿Cómo puedo asegurarme de que studentList.type devuelva Array .

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

studentList en su código siempre será una matriz, vacía cuando inicialice el estado. Si desea verificar si hay algo en la matriz, debe usar studentList.length

about 4 years ago · Santiago Trujillo Report

0

Como se menciona en los comentarios, las matrices no tienen una propiedad de type .

Su valor de estado studentList siempre es una matriz; no hay necesidad de comprobar su tipo.

Una cosa que parece estar haciendo incorrectamente es actualizar studentList cuando hace clic en su botón ( <div> ). En resumen, realmente no debería necesitar usar métodos DOM en React.

Para actualizar su matriz con el valor de su estado de input , use esto...

 const handleClick = () => { setStudentList((prev) => [input, ...prev]); setInput(""); };

y

 <div id="add-students-button" onClick={handleClick}> <p>Add</p> </div>

Consulte useState - Actualizaciones funcionales para obtener información sobre cómo estoy usando setStudentList()

about 4 years ago · Santiago Trujillo Report

0

Aunque los colaboradores anteriores resolvieron su problema eliminándolo en otro lugar, me gustaría responder esto:

¿Cómo puedo asegurarme de que studentList.type devuelva Array?

Si quiere asegurarse de que su variable sea una matriz, puede usar el método estático isArray() de Array:

 Array.isArray(studentList) // returns true if array or false if not
about 4 years ago · Santiago Trujillo 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!