我得到了错误:TypeError: Cannot read property 'map' of undefined
当我试图构建一个 const 值以注入到 Gallery 中时。使用const
JSON 构建
这是发生问题的类:
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;
我不明白它为什么抱怨。任何想法 ?谢谢