ReactJS - TypeError: Невозможно прочитать свойство 'raw' из неопределенного - PullRequest
1 голос
/ 29 января 2020

Я пытаюсь получить данные от части API, которая похожа на эту, и на самом деле я могу видеть все данные в консоли.

{ 
  "id":"DszAeHV8zfQ",
  "created_at":"2020-01-28T19:41:06-05:00",
  "updated_at":"2020-01-29T05:54:02-05:00",
  "promoted_at":"2020-01-29T05:54:02-05:00",
  "width":3887,
  "height":5595,
  "color":"#1E130A",
  "description":"Yet another sleeping koala. I am not happy with the lighting in this photo, where the koala is in the deep shade of an orange/brown tarpaulin (which is needed to give them shelter from the rain and the sun), and the bright light background, but I can't help being amused by the way they can sleep anywhere in any position.",
  "alt_description":null,
  "urls":{ 
     "raw":"https://images.unsplash.com/photo-1580258387643-65bb85ef9c61?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjExMjkzNX0",
     "full":"https://images.unsplash.com/photo-1580258387643-65bb85ef9c61?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjExMjkzNX0",
     "regular":"https://images.unsplash.com/photo-1580258387643-65bb85ef9c61?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjExMjkzNX0",
     "small":"https://images.unsplash.com/photo-1580258387643-65bb85ef9c61?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjExMjkzNX0",
     "thumb":"https://images.unsplash.com/photo-1580258387643-65bb85ef9c61?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&ixid=eyJhcHBfaWQiOjExMjkzNX0"
  },
  "links":{ 
     "self":"https://api.unsplash.com/photos/DszAeHV8zfQ",
     "html":"https://unsplash.com/photos/DszAeHV8zfQ",
     "download":"https://unsplash.com/photos/DszAeHV8zfQ/download",
     "download_location":"https://api.unsplash.com/photos/DszAeHV8zfQ/download"
  },
  "categories":[ 

  ],
  "likes":2,
  "liked_by_user":false,
  "current_user_collections":[ 

  ],
  "user":{ 
     "id":"TYLyWjPA9BM",
     "updated_at":"2020-01-29T05:54:02-05:00",
     "username":"davidclode",
     "name":"David Clode",
     "first_name":"David",
     "last_name":"Clode",
     "twitter_username":null,
     "portfolio_url":"http://tracts4free.wordpress.com",
     "bio":"I enjoy photography, painting, and nature. I lived in South Africa, the UK, and now Australia. More free paintings, photos available at Tracts4Free.WordPress.com, and Reforestation.me. Also now on YouTube.",
     "location":"Cairns, Queensland, Australia.",
     "links":{ 
        "self":"https://api.unsplash.com/users/davidclode",
        "html":"https://unsplash.com/@davidclode",
        "photos":"https://api.unsplash.com/users/davidclode/photos",
        "likes":"https://api.unsplash.com/users/davidclode/likes",
        "portfolio":"https://api.unsplash.com/users/davidclode/portfolio",
        "following":"https://api.unsplash.com/users/davidclode/following",
        "followers":"https://api.unsplash.com/users/davidclode/followers"
     },
     "profile_image":{ 
        "small":"https://images.unsplash.com/profile-1503350572760-b44aa5280785?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32",
        "medium":"https://images.unsplash.com/profile-1503350572760-b44aa5280785?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64",
        "large":"https://images.unsplash.com/profile-1503350572760-b44aa5280785?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128"
     },
     "instagram_username":null,
     "total_collections":11,
     "total_likes":16469,
     "total_photos":676,
     "accepted_tos":true
  }

}

Я могу получить поля "id", "creation_at". но я не могу получить эти вложенные объекты, такие как "urls", "links"

Я пытался получить эти данные, используя обозначение объекта следующим образом:

<img src={this.state.photo.urls.raw} alt="" />

Но это выдает ошибку:

TypeError: Cannot read property 'raw' of undefined 

Моя функция извлечения выглядит так:

 getPhoto = () => {
    fetch(`https://api.unsplash.com/photos/${this.state.photoId}?client_id=API_KEY`)
        .then(res => res.json())
        .then(data => {
            this.setState({ photo: data });
            console.log(this.state.photo);
        })
        .catch(err => console.log(err));
}

Мои состояния:

constructor(props) {
    super(props);
    this.state = {
        photo: [],
        photoId: this.props.match.params.photoId,
    }
}

1 Ответ

1 голос
/ 29 января 2020

Это происходит потому, что при первом рендеринге this.state.photo является массивом

constructor(props) {
    super(props);
    this.state = {
        photo: [],
        photoId: this.props.match.params.photoId,
    }
}

И не имеет свойства url.

Чтобы исправить это, вы должны

Измените photo на и объект

constructor(props) {
    super(props);
    this.state = {
        photo: {}, // object
        photoId: this.props.match.params.photoId,
    }
}

Проверьте, существует ли this.state.photo.url, прежде чем получить к нему доступ

<img src={this.state.photo.urls && this.state.photo.urls.raw} alt="" />

Вы также можете иметь значение по умолчанию src, когда изображение еще не загружено.

<img src={this.state.photo.urls ? this.state.photo.urls.raw : 'default url'} alt="" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...