我的前端代码有一个 get 请求。
fetch('/usershop', {
method: 'GET',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
}
})
.then(res=> res.json())
.then(res=> {
var obj = {}
//error found here
res.map(item=> {
obj[item["_id"]]={stations: item.locations.stations, position: item.locations.position, yourshopname: item.locations.yourshopname, items: item.items }}
)
this.setState({stations: obj})
})
.catch(err=> console.log(err)) }
当我在最后的 .then 之后 console.log "res" 时,我得到了一个对象数组。下面是其中一个对象的示例。换句话说,下面是一个 res 项。他们都有位置
0:
accepts:[]
firstname: "jon"
items:[{…}]
lastname:"lee"
locations:{position: Array(2), _id: "3lkj2jt390fgs90", stations:
"21lkjfoadf0j204j2", yourshopname: "jshop", __v: 0}
messages:[]
password:"kajdflka"
username:"alkklagf"
__v:2
_id:"lkjgaklfjgalkfdjglkaj"
__proto__:Object
但是当我尝试映射它时,它给了我错误:无法读取未定义的“站”的属性。
当我尝试 console.logging item._id 等时,一切都解决了。
我什么时候开始收到错误消息:当我刚刚在本地主机上运行时,我的 gitignore 文件中有 /build。这一切都很好。但我想把它放在 heroku 云上。所以我从 gitignore 文件中取出 /build 并运行 npm run build。一旦我这样做了,即使我只是在我的本地主机上运行它,它也会停止工作。
请帮忙!仅供参考,我需要将每个对象都转换为该格式,因为我使用的是 Mapbox API gl react api。https://github.com/alex3165/react-mapbox-gl
在执行获取请求之前,您必须创建一个空对象以进行映射。(例如,在安装组件时,或在构造函数中)
否则 map 函数会尝试映射一个未定义的对象,因为 fetch-call 是异步的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句