簡體   English   中英

當 map 函數在代碼中時,它返回 undefined,當 console.log 時,它返回一個空對象和一個數據。 我只想要數據

[英]when map function is in the code it returns undefined and when console.log it returns the an empty object and an the data. i just want the data

import React, { useState, useEffect } from 'react';

const Slide = () => {

     let [nasaDa, setData] = useState({}); 

        function fetchData() { //fetch function to get the data from the server
            fetch('/done')
            .then(response => response.json())
            .then(data => {
                setData(data) // Prints result from `response.json()` in getRequest
            })
            .catch(error => console.error(error)) //console.log if there is an error with fetching data 
        }

     useEffect(() => {
         fetchData();   //calling the fetch function 
     }, [])

     return(
         <div className="slide" >
             {nasaDa.map((item, index) => { //mapping the data that should be returned from nasaDa
                 return [
                     <div key={index} className='mapDiv'>
                         <h>{item.name}</h>, 
                         <img src={item.img}/>, //mapping out the data from array 
                         <p>{item.des}</p>
                 ]
             })}
         </div>
     )
export default Slide;

返回時,它給出{} [{data}]

我需要的只是[{data}]

像這樣嘗試:

let [nasaDa, setData] = useState(null); 

    function fetchData() { //fetch function to get the data from the server
        fetch('/done')
        .then(response => response.json())
        .then(data => {
            setData(data) // Prints result from `response.json()` in getRequest
        })
        .catch(error => console.error(error)) //console.log if there is an error with fetching data 
    }

 useEffect(() => {
     fetchData();   //calling the fetch function 
 }, [])

 return(
     <div className="slide" >
         {nasaDa && nasaDa.map((item, index) => { //mapping the data that should be returned from nasaDa
             return <div key={index} className='mapDiv'>
                     <h>{item.name}</h>, 
                     <img src={item.img}/>, //mapping out the data from array 
                     <p>{item.des}</p>
            </div>
         })}
     </div>
 )

獲取數據是異步的,您需要一種機制來了解您的數據是否已加載。 我將初始狀態設置為 null 並在地圖之前添加了一個檢查,這樣你就不會得到任何渲染。 您可以選擇在該狀態下渲染微調器或其他內容。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM