我正在尝试从端点获取类(class)中包含的简单类(class)列表。
如果我尝试console.log(this.state.course.lessons)
显示包含 3 个项目的数组。
但是,如果我尝试 console.log(this.state.course.lessons.map(//function)
我不断得到
TypeError: this.state.course.lessons is undefined
如何将函数映射到类(class)数组,以便我可以将它们呈现为列表。 组件
import React, { Component } from 'react'
export class CourseDetail extends Component {
constructor(props) {
super(props);
this.state = {
course: []
};
}
componentDidMount() {
fetch(`http://127.0.0.1:8000/api/courses/${this.props.match.params.id}`)
.then(res => res.json())
.then((course) => {
this.setState({
course: course,
});
console.log(this.state.course.lessons)
});
}
render() {
return (
<div>
{this.state.course.lessons.map((lesson)=>(console.log(lesson)))}
<h1>{this.state.course.title}</h1>
</div>
)
}
}
export default CourseDetail
从端点返回的json
{
"id": 1,
"lessons": [
1,
2,
3
],
"owner": 1,
"rating": 0,
"title": "Course 1",
"description": "course 1 desc",
"pub_date": "2019-11-23",
"is_live": false,
"category": 1
}
最佳答案
最明显的解决方案就是为对象提供默认状态(如果您想访问它):
constructor(props) {
super(props);
this.state = {
course: {
lessons: []
}
};
}
关于javascript - 类型错误 : variable is undefined despite being able to log the variable correctly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59095854/