简体   繁体   English

我不知道为什么状态未定义?

[英]I can't figure out why state is undefined?

I am trying to make call to Unsplash API to return images based on location strings passed down from props. 我试图调用Unsplash API,以根据从道具传来的位置字符串返回图像。

When I console log this.state.props the response json object is there. 当我在控制台上登录this.state.props时,响应json对象在那里。 But when I try to get the image urls off of state and use them as the source for an image, I keep getting an error that says "can't read property small of undefined". 但是,当我尝试使图像URL脱离状态并将其用作图像源时,我不断收到一条错误消息,内容为“无法读取未定义的属性”。

Am I overlooking something? 我在俯视什么吗?

import React, {Component} from 'react';
import Unsplash, {toJson} from 'unsplash-js';



const unsplash = new Unsplash({
  applicationId: {process.env.ID},
  secret: {process.env.SECRET},
  callbackUrl: {process.env.CALLBACK}
});


export default class Photos extends Component{
    constructor(props){
        super(props);

        this.state = {
            photo:[]
        }


        this.getPhotos = this.getPhotos.bind(this);
    }

    componentWillMount(){
        this.getPhotos();
      }

      getPhotos(){

          unsplash.search.photos(`${this.props.place}`,1,1)
          .then(toJson)
          .then(json => {
            this.setState({photo: json.results})
            console.log(this.state.photo)
          })


      }

      render(){

        return (
            <div>
                {

                 this.state.photo ? <img src = {this.state.photo.urls.small}/>:<div>loading</div>
                }

              </div>
              )
            }
}

this.state.photo is an array. this.state.photo是一个数组。 An array does not have a property urls (therefore undefined ). 数组没有属性urls (因此为undefined )。 Trying to access the property small of undefined will raise the error. 尝试访问undefined small属性将引发错误。

You will have to loop through your photos and render each image. 您将必须遍历照片并渲染每个图像。 Example

render() {
  [...]
  this.state.photo.map((singlePhoto) => (
    <img src={singlePhoto.urls.small} />
  ))
  [...]

Your state needs to have the nested value set to something in order for this to work. 您的州需要将嵌套值设置为某种值才能起作用。

For instance,you are using this.state.photo.urls.small but your state is only an empty array. 例如,您正在使用this.state.photo.urls.small但您的状态只是一个空数组。

One way to fix this would be to set it to null if this.state.photo is not defined. 解决此问题的一种方法是,如果未定义this.state.photo,则将其设置为null。 Also you might want to use this.state.photo.map and a nested component instead of directly trying to access urls. 另外,您可能要使用this.state.photo.map和嵌套组件,而不是直接尝试访问url。

Example: 例:

return (
    <div>
        this.state.photo.length ? this.state.photo.map(p => <div>
            <img src = {p.urls.small}/>
       </div>
       :<div>loading</div>
  </div>;

)

很简单,您可以检查array.length是否存在,而不是在该数组上使用map,并且每个图片都将在数组的回调中,因此可以在img标签中使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM