未捕获(在承诺中)TypeError:无法读取未定义的“站点”的属性

问题描述 投票:-1回答:1

我的前端代码有一个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之后调试.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等等时,一切都解决了。

我什么时候开始收到错误:当我刚刚在localhost上运行时,我/我的gitignore文件已经构建了。一切都很好。但是我想把它放在heroku云上。所以我从gitignore文件中取出/ build并运行npm run build。一旦我这样做,即使我在我的本地主机上运行它,它也会停止工作。

请帮忙!仅供参考,我需要将每个对象都放入该格式,因为我正在使用Mapbox API gl react api。 https://github.com/alex3165/react-mapbox-gl

javascript mongodb reactjs heroku
1个回答
0
投票

在执行获取请求之前,必须创建一个要映射的空对象。 (例如,在组件的安装上,或在构造函数中)

否则map函数会尝试映射未定义的对象,因为fetch-call是异步的。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.