无法读取属性'长度'检查数组时为null

时间:2018-05-23 15:28:04

标签: reactjs react-component

我试图在网站上展示一些照片。我每次尝试都会收到此错误:

  

无法读取属性'长度'为null

import React, { Component } from 'react';
import axios from 'axios';


class ImagePlayer extends Component {
constructor(props) {
    super(props);
    this.state = {
        photos: null
    };
}

componentDidMount() {
    axios.get(`/api/gameDev/image-files/${this.props.charId}/pics`)
        .then((response) => {
            this.setState({ photos: response.data })
        })
        .catch((error) => {
            console.log(error);
        });

}

showMedia = (props) => {
    return (
        <div>
            {
                props.photos.length > 0 &&
                    <div>
                        {props.photos.map((photo) => photo.title)}
                    </div>
            }
        </div>
    );
}

render() {
    return (
        <div>
            <div>Show Media</div>
            <div>
                {this.showMedia(this.state)}
            </div>
        </div>
    );
}

}

导出默认ImagePlayer;

我知道我做错了什么。如果有人能看到任何东西,请告诉我。

谢谢! :)

2 个答案:

答案 0 :(得分:2)

将初始photos状态设置为空数组:

this.state = {
    photos: []
};

或者,将props.photos.length > 0更改为:

props.photos && props.photos.length > 0 // or (props.photos || []).length > 0

答案 1 :(得分:1)

第一次安装渲染时,状态将照片显示为空。您需要将其设置为初始空数组,以便此阶段不会失败:

this.state = {
  photos: []
};