React类组件调用this.showDate报错:Cannot read property 'showDate' of undefined
解决React类组件中map回调里
this为undefined的问题 嘿,我完全懂你现在的困扰——在filterCourses里调用map时,普通函数回调里的this丢失了指向,导致找不到组件的showDate方法。下面给你几个简单有效的解决办法:
方法1:使用箭头函数作为map的回调
箭头函数不会创建自己的this,它会继承外层作用域的this(也就是你的组件实例)。直接把map里的普通函数换成箭头函数就行:
filterCourses() { let courseRows = []; // 注意:数组不能用 != [] 判断,引用类型的比较无效,改用长度判断 if (this.props.upcoming_training && this.props.upcoming_training.length > 0) { courseRows = this.props.upcoming_training.map((course, index) => { return ( // 一定要给列表项加key属性,这是React列表的强制要求 <tr key={index}> <th><button className='btn btn-sm btn-primary'> More Info </button></th> <td>{course.Course}</td> <td> {(course.Name.includes("OL -") ? course.Name.slice(5) : course.Name)}</td> <td>{this.showDate(course.Start)}</td> <td>{this.showDate(course.End)}</td> <td>{(course.IsOnline ? "Online" : "On-Site")}</td> </tr> ) }) } return courseRows; }
方法2:提前保存this的引用
在filterCourses函数开头,把组件的this存到一个变量里(比如self),然后在回调里用这个变量代替this:
filterCourses() { let courseRows = []; const self = this; // 保存组件的this引用 if (this.props.upcoming_training && this.props.upcoming_training.length > 0) { courseRows = this.props.upcoming_training.map(function(course, index) { return ( <tr key={index}> <th><button className='btn btn-sm btn-primary'> More Info </button></th> <td>{course.Course}</td> <td> {(course.Name.includes("OL -") ? course.Name.slice(5) : course.Name)}</td> <td>{self.showDate(course.Start)}</td> {/* 用self代替this */} <td>{self.showDate(course.End)}</td> <td>{(course.IsOnline ? "Online" : "On-Site")}</td> </tr> ) }) } return courseRows; }
方法3:给map的回调绑定this
在普通函数后面用.bind(this)来强制绑定组件的this:
filterCourses() { let courseRows = []; if (this.props.upcoming_training && this.props.upcoming_training.length > 0) { courseRows = this.props.upcoming_training.map(function(course, index) { return ( <tr key={index}> <th><button className='btn btn-sm btn-primary'> More Info </button></th> <td>{course.Course}</td> <td> {(course.Name.includes("OL -") ? course.Name.slice(5) : course.Name)}</td> <td>{this.showDate(course.Start)}</td> <td>{this.showDate(course.End)}</td> <td>{(course.IsOnline ? "Online" : "On-Site")}</td> </tr> ) }.bind(this)) // 绑定this到组件实例 } return courseRows; }
另外补充两个小细节:
- 你原来代码里
if (this.props.upcoming_training != [])的判断逻辑无效,因为数组是引用类型,[] != []永远为true,改成判断数组是否存在且长度大于0更合理 - React列表元素必须加
key属性,否则会触发控制台警告,上面的示例里已经补上了key={index}(如果课程有唯一ID的话,用ID作为key会比index更优)
内容的提问来源于stack exchange,提问作者Dustin Wells
相关产品推荐
相关产品推荐

