React propType 无法读取未定义的属性 [英] React propType cannot read property of undefined
问题描述
使用 propTypes 来验证 props 会出现以下错误:
<块引用>类型错误:无法读取未定义的属性字符串".
类型错误:无法读取未定义的属性func".
有问题的代码位于代码段的底部:
从'react'导入React;从./ProjectItem"导入项目项目;类项目扩展了 React.Component {删除项目(标题){this.props.onDelete(title);}使成为() {让项目项;如果(this.props.project){projectItems = this.props.project.map(project => {返回 (<ProjectItem key={project.title} project={project} onDelete={this.deleteProject.bind(this)}/>)});}返回 (<div className=项目">{项目项目}
);}}项目.propTypes = {项目:React.PropTypes.string,onDelete: React.PropTypes.func}
需要安装prop-types
包,然后添加import语句
从 prop-types 导入 PropTypes;
在班级中名列前茅.
PropTypes 已从 React 移至它们自己的包 prop-types
.
如评论中所述,这仅适用于 React 15.5 及更高版本.
Using propTypes to validate props gives the following error:
TypeError: Cannot read property 'string' of undefined.
TypeError: Cannot read property 'func' of undefined.
The code in question is at the bottom of the snippet:
import React from 'react';
import ProjectItem from './ProjectItem';
class Projects extends React.Component {
deleteProject(title) {
this.props.onDelete(title);
}
render() {
let projectItems;
if (this.props.project) {
projectItems = this.props.project.map(project => {
return (
<ProjectItem key={project.title} project={project} onDelete={this.deleteProject.bind(this)} />
)
});
}
return (
<div className="Projects">
{projectItems}
</div>
);
}
}
Projects.propTypes = {
projects: React.PropTypes.string,
onDelete: React.PropTypes.func
}
You need to install the prop-types
package and then add the import statement
import PropTypes from prop-types;
at the top of your class.
The PropTypes have been moved from React to their own package prop-types
.
EDIT: As mentioned in the comments, this is only applicable for React version 15.5 and above.
这篇关于React propType 无法读取未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!