TypeError:解析 JSON 时无法读取未定义的属性“地图”

IT技术 javascript reactjs
2022-07-13 23:48:44

我得到了错误:TypeError: Cannot read property 'map' of undefined当我试图构建一个 const 值以注入到 Gallery 中时。使用constJSON 构建

这是发生问题的类:


class ClassDetails extends React.Component {
    
    constructor(props, context) {
        super(props);
        this.state = {anchorEl: null, 
            showJoin: false,
            classDetailsInfo: ''};
    }


    componentDidMount = () => {
        this.setState({classDetailsInfo: ClassDataUseCase.getClassDetails()})
    }

      render() {

        const CLASS_PIC_LIST = this.state.classDetailsInfo.classpic
        const GALLERY = CLASS_PIC_LIST.map((pic) => ({
            src: pic,
            thumbnail: pic, //.replace("1280","_480"), // for example
            thumbnailWidth: 156,
            thumbnailHeight: 156
            }));
       ...
    }
}

export default ClassDetails;

确切的错误是TypeError: Cannot read property 'map' of undefined并且在执行时发生const GALLERY = CLASS_PIC_LIST.map((pic) => ({

使用classDetailsInfo定义ClassDataUseCase.getClassDetails()如下:

class ClassDataUseCase {

    static getAllClasses() {
        return JSON.parse(ClassDetailsData.Classes)
    }
    static getClassDetails(id) {
        var jsonClasses = JSON.parse(ClassDetailsData.Classes);
        for(let k=0;k< jsonClasses.length;k++){
            if(jsonClasses[k].id===id){
              return jsonClasses[k];
            }
        }
    }
}

并且数据来自ClassDetailsData如下定义的 JSON:

class ClassDetailsData {
    static Classes = [{
            "id": "c000001",
            "title": "Cook like a chef",
            "price": "5",
            "teacher": "Arthur Patrick",
            "teacherpic": "https://cdn.pixabay.com/photo/2015/03/03/08/55/portrait-657116_1280.jpg",
            "teacherid": "u0000000001",
            "desc": "Always want to learn to cook, that's the place you need to be",
            "bring": "Your fun , your motivation and you",
            "tags": [],
            "address": {
                "id":"",
                "Name": "Joel Robuchon",
                "address1": "3799 S Las vegas boulevard",
                "address2": "",
                "city": "las vegas",
                "county": "Clark",
                "zip": "89109",
                "state": "Nevada",
                "country": "United States"
            },
            "date": "2021/09/01",
            "time": "1:00PM",
            "duration": "2",
            "classpic": ["https://cdn.pixabay.com/photo/2014/06/16/23/10/spice-370114_1280.jpg",
            "https://cdn.pixabay.com/photo/2015/08/13/18/47/spices-887348_1280.jpg", 
            "https://cdn.pixabay.com/photo/2015/04/20/13/30/kitchen-731351_1280.jpg",
            "https://cdn.pixabay.com/photo/2015/07/02/10/40/writing-828911_1280.jpg"],
            "reviews": [{
                "name": "Gabby Caldwell",
                "profilePic":"https://cdn.pixabay.com/photo/2015/03/03/08/55/portrait-657116_960_720.jpg",
                "rate": "5",
                "total_review": "13",
                "text": "Rachel was such a kind and knowledgeable guide. She took us to see some hidden coves that a lot of tourists probabaly miss. I’m keeping the map I made FOREVER!!!"
            }],
        }, 
        {........}
        ];
}

export default ClassDetailsData;

我不明白它为什么抱怨。任何想法 ?谢谢

3个回答

可能存在this.state.classDetailsInfo.classpic没有value的情况。因此,如果它没有任何值,则initialize它具有默认值。[]

你可以这样做:

const CLASS_PIC_LIST = this.state.classDetailsInfo.classpic || [];

在中,constructor您将状态声明classDetailsInfo为空字符串,并且字符串上没有.map方法。

this.state = {anchorEl: null, 
            showJoin: false,
            classDetailsInfo: ''};

您需要将 声明classDetailsInfo为适当的类型,以免在初始渲染时中断。

this.state = {anchorEl: null, 
            showJoin: false,
            classDetailsInfo: {
              classpic: []
            }
};

在您的状态下,您将其定义classDetailsInfo为字符串,这就是您收到该错误的原因

您应该最初将它设置为一个空数组[]以避免意外行为

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      classList: ''
    }
  }
  
  componentDidMount() {
    this.setState({classList: ["name", "data", "test"]});
  }
  
  
  render() {
    return <div>
      {this.state.classList.map(cl => <span>{cl}</span>)}
    </div>
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.1.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.1.1/umd/react-dom.production.min.js"></script>


<div id="root"></div>

您可以查看这个简单的示例,如果我将状态键的值更改为classList每件事[] 都按预期工作。但是现在它重现了您得到的相同错误

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      classList: []
    }
  }
  
  componentDidMount() {
    this.setState({classList: ["name", "data", "test"]});
  }
  
  
  render() {
    return <div>
      {this.state.classList.map(cl => <span>{cl}</span>)}
    </div>
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

在我将 classList 初始化为数组之后的第二个示例中,它可以工作。