0

我正在尝试在网站上展示一些照片。每次我尝试,我都会收到这个错误:

无法读取 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;

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

谢谢!:)

4

2 回答 2

4

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

this.state = {
    photos: []
};

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

props.photos && props.photos.length > 0 // or (props.photos || []).length > 0
于 2018-05-23T15:33:15.260 回答
1

第一次安装渲染时,状态中的照片为空。您需要将其设置为初始空数组,这样这个阶段就不会失败:

this.state = {
  photos: []
};
于 2018-05-23T15:34:30.717 回答