如何解决如何在ReactJS挂钩中映射数据?
我想通过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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。