简体   繁体   中英

How to render array of objects in Reactjs using useState?

I am working on a mern project. and I want to render an array of objects in my react page through my database by using useState.

The structure of database is数据库结构

my code

import React,{useEffect,useState} from 'react'
import { NavLink,useParams } from 'react-router-dom'
import Adminbar from './Adminbar'

const Contracter = () => {
    const { id } = useParams();
    const [member,setMember] = useState([])

    const tofetchallmember = async ()=>{
        try {
  
            const res = await fetch(`/member/${id}`,{
                method :"GET",
                headers : {
                    Accept : "application/json",
                    "Content-Type" : "application/json"
                },
                credentials : "include"
            })
  
            const data = await res.json()
            setMember(data)
            console.log(data.name);
            console.log(data.projectmembers[0]);
            console.log(data.projectmembers[0].attendance);
            
        } catch (error) {
            console.log(error);         
        }
    }

   

    useEffect(() => {
        tofetchallmember()
    }, [])

    return (
        <>

      
        <Adminbar/>
     
            <div className='container mt-5'>
                <div className='row'>
                    <div className='col-sm-5 col-md-5 col-lg-5'>
                        <div class="row align-items-md-stretch">

                            <div class="h-100 p-5 text-bg-light rounded-3">
                                <h2>Contracter List of {member.name}</h2>
                                <ol class="list-group list-group-numbered mt-5

To achieve this I tried the above code. If I tried this:

            setMember(data)
            console.log(data.name);
            console.log(data.projectmembers[0]);
            console.log(data.projectmembers[0].attendance);

it perfectly shows all the data in my console but when I tried to render it in my html code through this:

<h2>Contracter List of {member.projectmembers[0].name}</h2>

it shows the following error:

Uncaught TypeError: Cannot read properties of undefined (reading '0')

The problem is caused because in the first render your state member is an empty array, so when it tries to access projectmembers[0].name it crashes. You should use optional chaining (?.) operator to solve with your actual code <h2>Contracter List of {member?.projectmembers[0]?.name}</h2> or check if the array exists:

const Contracter = () => {
  //all the previous code
  return (
   {member.length===0 ? <p>No data</p> : member?.projectmembers[0]?.name}
  )
}

Initially, when the component is loaded, the member state is an empty array [] . So you will not have any data in the state, you cannot access member.projectmembers

Put a validation to check if the member object has projectmembers or not as below.

 { member.projectmembers && member.projectmembers.length > 0 ? <h2>Contracter List of {member.projectmembers[0].name}</h2> : null}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM