【问题标题】:TypeError while looping on the response循环响应时出现 TypeError
【发布时间】:2021-04-21 06:13:54
【问题描述】:

我收到错误:

TypeError: Cannot read property 'url' of undefined

当我像这样循环响应时:

  getPhoto = (venueId) => {
    const PhotoEndpoint = `https://api.foursquare.com/v2/venues/${venueId}/photos?`;
    const parameters = {
      client_id: "my client_id",
      client_secret: " my client_secret",
      group: "venue",
      limit: "100",
      v: "20211301",
    };
 axios
      .get(PhotoEndpoint + new URLSearchParams(parameters))
      .then((response) => {
        for (var i = 0; i < response.data.response.photos.items.length; i++) {
          this.setState({
            photosUrl:
              response.data.response.photos.items[i].prefix +
              "original" +
              response.data.response.photos.items[i].suffix,
          });
        }
      })
      .catch((error) => {
        console.log(" My photo Error : " + error);
      });
  };

我收到的数据是这样的: https://foursquare.com/developers/explore#req=venues%2F43695300f964a5208c291fe3%2Fphotos%3F

或者我也把它贴在这里,以防链接失效:

{
  data: {
    meta: {
      code: 200,
      requestId: "6002bcf5c8ba5b3c6d668965",
    },
    notifications: [{
      type: "notificationTray",
      item: {
        unreadCount: 5,
      },
    }, ],
    response: {
      photos: {
        count: 30,
        items: [{
          id: "51b8f916498e6a8c16a329eb",
          createdAt: 1371076886,
          source: {
            name: "Instagram",
            url: "http://instagram.com",
          },
          prefix: "https://fastly.4sqi.net/img/general/",
          suffix: "/26739064_mUxQ4CGrobFqwpcAIoX6YoAdH0xCDT4YAxaU6y65PPI.jpg",
          width: 612,
          height: 612,
          user: {
            id: 26739064,
            firstName: "Darius",
            lastName: "Alonzo",
            gender: "male",
            countryCode: "US",
            photo: {
              prefix: "https://fastly.4sqi.net/img/user/",
              suffix: "/BWWLKDFKJ4VOVFXK.jpg",
            },
          },
          checkin: {
            id: "51b8f915498e481c2e86de41",
            createdAt: 1371076885,
            type: "checkin",
            timeZoneOffset: -240,
          },
          visibility: "public",
        }, ],
      },
    },
  }
};

会有超过 100 个项目。 我试图让 prefix 将它与 original 的大小连接起来,然后再次连接 suffix 以创建一个 URL,然后 setState我的 PhotoUrl 和后来渲染每张照片,但我得到 TypeError 我做错了什么?

【问题讨论】:

标签: javascript json reactjs axios foursquare


【解决方案1】:

您的架构不包含源元素。也许你需要把照片元素的前缀和后缀结合起来。

【讨论】:

  • 架构在data.response.photos.items[0]中包含source,内容为source: { name: "Instagram", url: "http://instagram.com", }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 1970-01-01
相关资源
最近更新 更多