Javascript JS+中的变量;API使用:分析错误:意外令牌

Javascript JS+中的变量;API使用:分析错误:意外令牌,javascript,reactjs,restapi,Javascript,Reactjs,Restapi,我对React和Javascript都是新手,我正在尝试构建一个使用RESTAPI的页面。除了我想从API中提取的数据之外,它工作得很好,但它似乎不起作用。 在数据变量中,是来自API端点的副本。const-teacherMapped和lessonsMapped工作正常,但与之基本相同的const-teachers在以下方面失败: Line 97:37 'teachers' is not defined no-undef 从注释代码中可以看到,我尝试在不同的位置声明变量,但没有成功。 你能给

我对React和Javascript都是新手,我正在尝试构建一个使用RESTAPI的页面。除了我想从API中提取的数据之外,它工作得很好,但它似乎不起作用。 在数据变量中,是来自API端点的副本。
const-teacherMapped
lessonsMapped
工作正常,但与之基本相同的
const-teachers
在以下方面失败:

 Line 97:37 'teachers' is not defined no-undef
从注释代码中可以看到,我尝试在不同的位置声明变量,但没有成功。 你能给我一些如何做对的提示吗? 这是我的密码:

import React, {Component} from 'react';
import Card from '@material-ui/core/Card'
import CardActions from '@material-ui/core/CardActions'
import CardContent from '@material-ui/core/CardContent'
import CardMedia from '@material-ui/core/CardMedia'
import Button from '@material-ui/core/Button'
import Typography from '@material-ui/core/Typography'
import AppbarMui from './components/AppbarMui'
import {Link } from 'react-router-dom';
import { withCookies, Cookies } from 'react-cookie'

const data = 
  {
    "id": 1,
    "title": "Potion-Making - Beginner's course",
    "description": "This highly-rated online course will guide you step-by-step through the composition of your first potion and other related aspects of potion-making",
    "lessons": [
        {
            "id": 1,
            "title": "Induction - What is a potion making?",
            "description": "What is a potion making and what will you need during our course?",
            "course": "Potion-Making - Beginner's course"
        }
    ],
    "teacher": [
        {
            "teacher_name": "John Doe"
        }
    ]
}

const teacherMapped = data.teacher.map(tea => (tea.teacher_name))

const lessonsMapped = data.lessons.map(less => (less.description))

class CourseView extends Component { 

    state = {
        oneCourse: []

    };

    componentDidMount() {
    fetch(`${process.env.REACT_APP_API_URL}${window.location.pathname}`)
        .then(res => res.json())
        .then((data) => {
            this.setState({ oneCourse: data })
        })
        .catch(error => console.log)

const teachers = this.state.oneCourse.teacher.map(tea => { return `${tea.teacher_name}`})

}


enroll = event => {
    let cookieValue = (document.cookie.match(/^(?:.*;)?\s*apitoken\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]
    if (cookieValue.length > 0) {
            fetch(`${process.env.REACT_APP_API_URL}${window.location.pathname}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 
                            'Authorization': `Token ${cookieValue}`},
                body: JSON.stringify(this.props.cookie)
                }).then( resp => resp.json())
                .then( res => {
                    alert (res)
                })
                .catch( error => console.log(error))}
    else {
        alert ('An Error occurred!')
    }}

  //teachersMapped =()=> {if (!this.state.oneCourse.teacher){ this.state.oneCourse.teacher.map(tea => (tea.teacher_name))}};

//const teachers = this.state.oneCourse.teacher.map(tea => { return `${tea.teacher_name}`})

  render () {
    return(
        <div>
          <AppbarMui />
                <Card>

                    <CardMedia style={{height: 300}}
                    component="img"
                        image="../img/room.jpg"
                        />
                    <CardContent>

                        <Typography gutterBottom variant="headline" component="h2" color="secondary">
                            {this.state.oneCourse.title}
                        </Typography>
                        <Typography component="p">
                            {this.state.oneCourse.description}
                        </Typography>
                        <h4>Teacher</h4>
                        <Typography>
                        Teacher is {teachers || "To be determined"}
                        </Typography>
                        <h4>Lessons</h4>
                         <Typography>
                        {lessonsMapped || "To be continued"}
                        </Typography>
                    </CardContent>
                    <CardActions>
                        <Button size="small" color="secondary" target="_blank" onClick={this.enroll}>
                            Enroll on Course
                        </Button> 

                    </CardActions>
                </Card>

        </div>
   ) 
}


}
export default withCookies (CourseView)
import React,{Component}来自'React';
从“@material ui/core/Card”导入卡片
从“@material ui/core/CardActions”导入CardActions
从“@material ui/core/CardContent”导入CardContent
从“@material ui/core/CardMedia”导入CardMedia
从“@material ui/core/Button”导入按钮
从“@material ui/core/Typography”导入排版
从“./components/AppbarMui”导入AppbarMui
从'react router dom'导入{Link};
从“react cookie”导入{withCookies,Cookies}
常数数据=
{
“id”:1,
“标题”:“药剂制作-初学者课程”,
“说明”:“这门评价很高的在线课程将指导您一步一步地完成第一瓶药水的配制以及药水制作的其他相关方面”,
“教训”:[
{
“id”:1,
“标题”:“诱导-什么是药剂制造?”,
“描述”:“什么是药水制作,在我们的课程中你需要什么?”,
“课程”:“药剂制作-初学者课程”
}
],
“老师”:[
{
“教师姓名”:“约翰·多伊”
}
]
}
const teacherMapped=data.teacher.map(tea=>(tea.teacher\u name))
const lessonsmap=data.lessons.map(less=>(less.description))
类CourseView扩展组件{
状态={
一门课程:[]
};
componentDidMount(){
fetch(`${process.env.REACT\u APP\u API\u URL}${window.location.pathname}`)
.then(res=>res.json())
。然后((数据)=>{
this.setState({oneCourse:data})
})
.catch(错误=>console.log)
const teachers=this.state.oneCourse.teacher.map(tea=>{return`${tea.teacher\u name}})
}
注册=事件=>{
让cookieValue=(document.cookie.match(/^(?:.*)?\s*apitoken\s*=\s*([^;]+)(?:.*)$/)| |[,null])[1]
如果(cookieValue.length>0){
fetch(${process.env.REACT\u APP\u API\u URL}${window.location.pathname}){
方法:“POST”,
标题:{'Content-Type':'application/json',
'授权':`Token${cookieValue}`,
正文:JSON.stringify(this.props.cookie)
}).then(resp=>resp.json())
。然后(res=>{
警报(res)
})
.catch(错误=>console.log(错误))}
否则{
警报('发生错误!')
}}
//teachersMapped=()=>{if(!this.state.oneCourse.teacher){this.state.oneCourse.teacher.map(tea=>(tea.teacher\u name))};
//const teachers=this.state.oneCourse.teacher.map(tea=>{return`${tea.teacher\u name}})
渲染(){
返回(
{this.state.oneCourse.title}
{this.state.oneCourse.description}
老师
教师是{教师| |“待定”}
教训
{Lessonsmap | | |“待续”}
报名参加课程
) 
}
}
使用cookies导出默认值(CourseView)

您将教师定义为类的属性,因此请尝试
此操作。教师
可在类的方法中访问它。

您将教师定义为类的属性,因此请尝试
此操作。教师
可在类的方法中访问它。

这是一个范围界定问题。您可以在CourseView componentDidMount函数中定义教师变量。因此,此变量将不存在于渲染方法的范围内。您必须根据您的用例将变量设置为全局变量或组件状态。

这是一个范围问题。您可以在CourseView componentDidMount函数中定义教师变量。因此,此变量将不存在于渲染方法的范围内。您必须根据您的用例将变量设置为全局变量或组件的状态。

谢谢,这很有效(我真傻,竟然忘了它)。然而,现在我得到了
类型错误:无法读取未定义的属性“map”
,尽管老师肯定在API中。这一行:
teachersmap=()=>{if(This.state.oneCourse.teacher){This.state.oneCourse.teacher.map(tea=>(tea.teacher\u name))}不会抛出错误,但不会给我老师。。。你知道问题可能出在哪里吗?是的,听起来你的oneCourse数组没有正确填充你期望的数据。尝试在fetch中使用console.log来查看您从api返回的数据类型,并确保其格式符合您的预期。谢谢您,这样做很有效(我真愚蠢,竟然忘记了它)。然而,现在我得到了
类型错误:无法读取未定义的属性“map”
,尽管老师肯定在API中。此行:
teachersmap=()=>{if(This.state.oneCourse.teacher){This.state.oneCourse.teacher.map(tea=>(tea.teac