开发者问题收集

API 返回对象

2020-10-20
76

我尝试在使用 ReactJS 时从 RIDB API 获取数据。我获取了返回的数据

function TryFetch() {
    const [camps, setCamps] = useState([]);
    
    

    useEffect(() => {
        axios.get(api)
            .then( res => {
                console.log(res)
                setCamps(res.data)
            })
            .catch(err => {
                console.log(err);
            })
    }, [])

    return (

            <div>
                <ul>

                    {camps && camps.RECDATA.map(post => (
                        <li key={post.CampsiteID}>{post.CampsiteID}</li>

                    ))}
                    
                    
                    
                </ul>   
            </div>


        )
}

API 调用返回的数据

{
RECDATA: [

{
    CampsiteID: "23480",
    FacilityID: "232732",
    CampsiteName: "25",
    CampsiteType: "STANDARD ELECTRIC"
},

{
    CampsiteID: "25550",
    FacilityID: "232732",
    CampsiteName: "35",
    CampsiteType: "STANDARD ELECTRIC"
},

{
    CampsiteID: "27520",
    FacilityID: "232732",
    CampsiteName: "27",
    CampsiteType: "STANDARD ELECTRIC"
} 

]

}

如何循环遍历 React 中的对象以显示各个营地信息?我一直收到 TypeError:无法读取未定义的属性“map”

3个回答

您可以按如下方式使用:

const data = { RECDATA: [

{ CampsiteID: "23480", FacilityID: "232732", CampsiteName: "25", CampsiteType: "STANDARD ELECTRIC"},

{ CampsiteID: "25550", FacilityID: "232732", CampsiteName: "35", CampsiteType: "STANDARD ELECTRIC"},

{ CampsiteID: "27520", FacilityID: "232732", CampsiteName: "27", CampsiteType: "STANDARD ELECTRIC"}

]};

<ul>
   {
      data && data.RECDATA.map(recordItem => {
          return <li>{recordItem.CampsiteType}</li>
      });
   }
</ul>
Aadil Mehraj
2020-10-20

非常简单

您可以执行以下操作

var apiData={RECDATA: [{CampsiteID: "23480", FacilityID: "232732", CampsiteName: "25", CampsiteType: "STANDARD ELECTRIC"},{ CampsiteID: "25550", FacilityID: "232732", CampsiteName: "35", CampsiteType: "STANDARD ELECTRIC"},{ CampsiteID: "27520", FacilityID: "232732", CampsiteName: "27", CampsiteType: "STANDARD ELECTRIC"}]}

apiData.RECDATA.forEach(function(o){
   console.log(o.CampsiteID)
   console.log(o.CampsiteName)
})
In a React you can do something like below

 {
  data.RECDATA.forEach(recordItem => {
      return <li>{recordItem.CampsiteType}</li>
   });
 }
Negi Rox
2020-10-20
const result = { RECDATA: [

{ CampsiteID: "23480", FacilityID: "232732", CampsiteName: "25", CampsiteType: "STANDARD ELECTRIC"},
{ CampsiteID: "25550", FacilityID: "232732", CampsiteName: "35", CampsiteType: "STANDARD ELECTRIC"}, 
{ CampsiteID: "27520", FacilityID: "232732", CampsiteName: "27", CampsiteType: "STANDARD ELECTRIC"}
 
]};

<ul>
   {
      result && result.RECDATA.map(({CampsiteType}, index) =>
          <li key={`RECDATA_${index}`}>{CampsiteType}</li>
      );
   }
</ul>
Sarun UK
2020-10-20