React.js报错:Allcourse.js第20:35行提示'course'未定义no-undef如何解决
报错原因
这个no-undef报错是ESLint检测到代码中使用了未声明的变量course触发的。你当前提供的Allcourse.js代码中没有直接使用course变量,问题出在你引入的Course组件内部:
你在Allcourse组件中通过<Course course={item} />给子组件传递了名为course的属性,但Course组件没有正确接收这个props,直接在代码中使用了course变量,没有提前声明,因此触发报错。
也存在小概率是你本地运行的Allcourse.js代码存在笔误,比如把数组名courses错写为course调用,可以先核对下运行代码和你贴的代码是否一致。
修复方案
- 优先修改
Course.js组件,正确接收父组件传递的course属性,参考写法如下:
写法1:解构props直接拿到course
写法2:先获取整个props再提取courseimport React from 'react' const Course = ({ course }) => { // 后续直接使用course变量即可,示例如下 return ( <div> <h3>{course.title}</h3> <p>{course.description}</p> </div> ) } export default Courseimport React from 'react' const Course = (props) => { const course = props.course return ( <div> <h3>{course.title}</h3> <p>{course.description}</p> </div> ) } export default Course - 如果修改后还是报错,检查Allcourse.js中所有用到变量的位置,确认没有把
courses错写为course的笔误。
额外优化建议
你当前的useState命名可以调整得更符合规范,将setCourse改为setCourses,和前面的数组变量名courses对应,方便后续维护:
const [courses, setCourses] = useState([ { title: 'java course', description: 'this is demo' }, { title: 'react course', description: 'this is demo' }, { title: 'django course', description: 'this is demo' }, ])
内容的提问来源于stack exchange,提问作者Alok Kushwaha
相关产品推荐
相关产品推荐

