javascript - 类型错误 : variable is undefined despite being able to log the variable correctly

标签 javascript reactjs

我正在尝试从端点获取类(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/

相关文章:

javascript - 在不同的浏览器中打开 URL

javascript - 是否可以使用 javascript 从浏览器中获取 "read"mercurial repos?

javascript - React-bootstrap-autosuggest 的问题

javascript - react 不渲染类

javascript - 从嵌套 JavaScript 对象插入/删除数据

javascript - 如何在 JQTouch 工具栏 div 中水平显示列表元素(可能使用 CSS)

javascript - 捕获表单字段并用它们重新填充表单

javascript - 在 Sparx EA 中以编程方式克隆元素

javascript - react : Confusing behavior with useEffect and/or useState hooks

sublimetext - Sublime Text 有 JSX 格式化程序吗?