【问题标题】:Uncaught (in promise) TypeError: Cannot read property of 'stations' of undefinedUncaught (in promise) TypeError: Cannot read property of 'stations' of undefined
【发布时间】:2019-02-12 19:23:12
【问题描述】:

我的前端代码有一个获取请求。

  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" 时,我得到了一个对象数组。下面是其中一个对象的示例。换句话说,下面是一个资源项。他们都有位置

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 文件中有 /build 。一切都很好。但我想把它放在heroku云上。所以我从 gitignore 文件中取出 /build 并运行 npm run build。一旦我这样做了,即使我只是在本地主机上运行它,它也会停止工作。

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

【问题讨论】:

  • .catch(err => console.log(err)) 您可以这样做,以便在控制台中打印错误而不是破坏应用程序
  • 这是'res'的第一项,但是如果另一个项没有位置怎么办?你确定都有 .locations 吗?
  • 还注释该行 ...obj[] = ... 以确保该行有问题,因为您也有“站”作为状态变量,所以错误可能在另一个地点

标签: javascript mongodb reactjs heroku


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多