问题描述
我想通过API收集JSON数据并将其呈现为JSX来显示,但是我是新来反应钩子的人,我看到一个错误,说data.map不是一个函数 有人可以帮我吗?
这是我的代码
import React,{useState,useEffect} from "react";
import axios from "axios";
import ModalSubHeader from "../../styles/ModalSubHeader";
import CollectionHolder from "../../styles/CollectionHolder";
import {Collectionoption,CollectionoptionInner} from "../../styles/Collectionoption";
import CollectionIcon from "../../styles/CollectionIcon";
import CollectionIcons from "../../../../images/index";
function Collection(props) {
const [collectionList,setCollectionList] = useState(null);
useEffect(() => {
axios
.get("https://reg.my-waste.mobi/collections?project_id=556&district_id=556&zone_id=zone-z1250-z1261")
.then(({data}) => {
data = data.collection.types;
const collections = data.map((number) =>
<Collectionoption>
<CollectionoptionInner>
<CollectionIcon src={CollectionIcons[number.iconicShape]} />
{number.title}
</CollectionoptionInner>
</Collectionoption>
);
setCollectionList(collections)
})
console.log(CollectionIcons);
})
return(
<div>
<ModalSubHeader>What type of collection or event would you like to be reminded about?</ModalSubHeader>
<CollectionHolder>
{collectionList}
</CollectionHolder>
</div>
)
}
export default Collection;
解决方法
此端点返回的对象不是数组,因此您应该对其进行一些修改Object.values(data.collection.types).map(collection => {....})
,此代码可能有效:
import React,{useState,useEffect} from "react";
import axios from "axios";
import ModalSubHeader from "../../styles/ModalSubHeader";
import CollectionHolder from "../../styles/CollectionHolder";
import {CollectionOption,CollectionOptionInner} from "../../styles/CollectionOption";
import CollectionIcon from "../../styles/CollectionIcon";
import CollectionIcons from "../../../../images/index";
function Collection(props) {
const [collectionList,setCollectionList] = useState(null);
useEffect(() => {
axios
.get("https://reg.my-waste.mobi/collections? project_id=556&district_id=556&zone_id=zone-z1250-z1261")
.then(({data}) => {
data = data.collection.types;
setCollectionList(Object.values(data).map(item=> ({title:item.title,iconicShape:item.iconicShape})))
})
console.log(CollectionIcons);
})
return(
<div>
<ModalSubHeader>What type of collection or event would you like to be reminded
about?</ModalSubHeader>
<CollectionHolder>
{collectionList.map((number) =>
<CollectionOption>
<CollectionOptionInner>
<CollectionIcon src={CollectionIcons[number.iconicShape]} />
{number.title}
</CollectionOptionInner>
</CollectionOption>
)}
</CollectionHolder>
</div>
)
}
export default Collection;