React教程:TypeError:无法读取属性'道具'的未定义
React Tutorial: TypeError: Cannot read property 'props' of undefined
我决定学习React,并从官方教程开始。一切都很好,直到我的代码达到这种状态:
var CommentBox = React.createClass({
render: () => {
return (
<div className="commentBox">
<h1> Comments </h1>
<CommentList />
<CommentForm />
</div>
);
}
});
var CommentForm = React.createClass({
render: () => {
return (
<div className="commentForm">
Hello, world! I am a comment form;
</div>
);
}
});
var Comment = React.createClass({
rawMarkup: () => {
var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
return {__html: rawMarkup};
},
render: () => {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2> // <--- [[[[[[ ERROR IS HERE ]]]]]]
<span dangerouslySetInnerHtml={this.rawMarkup} />
</div>
);
}
});
var CommentList = React.createClass({
render: () => {
return (
<div className="commentList">
<Comment author="Pete Hunt">This is one comment</Comment>
<Comment author="Jordan Walke">This is *another* comment yo</Comment>
</div>
);
}
});
ReactDOM.render(
<CommentBox />,
document.getElementById('content')
);
当我尝试运行它时,我在devtools中得到以下错误:
TypeError:无法读取未定义的属性"props"
并且调试器在标记的行处暂停(参见代码)。当我将鼠标悬停在{this.props.author}
中的this
上时,我会预览具有props
属性的对象和所有内容。。。
使用函数声明(render() {}
或render: function {}
)而不是箭头函数render: () => {}
var Comment = React.createClass({
rawMarkup() {
var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
return {__html: rawMarkup};
},
render() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHtml={this.rawMarkup} />
</div>
);
}
});
Example
与函数表达式相比,
arrow function
表达式的语法更短,并且在词汇上绑定this值(不绑定自己的this、arguments、super或new.target)。箭头函数总是匿名的。
我收到了相同的错误消息:
无法读取未定义的属性"props"
但原因不同:当从函数内部调用this
时,javascript无法访问变量,因为this
位于外部范围内(注:我在ES5)
在这种情况下,只需将this
存储在函数之前的另一个变量中(在组件范围内):var that = this;
然后,您将能够从函数中调用that.props
。
希望这对其他收到错误信息的人有所帮助。
下面的详细示例:
render: function() {
var steps = [];
var that = this; // store the reference for later use
var count = 0;
this.props.steps.forEach(function(step) {
steps.push(<Step myFunction={function(){that.props.anotherFunction(count)}}/>); // here you are
count += 1;
});
return (
<div>{steps}</div>
)
}
发布/回答有点晚。
尝试将您的函数绑定到构造函数中
示例:
this.yourfunction = this.yourfunction.bind(this);
我在ES6上,箭头函数完成了任务:rawMarkup=()=>{}
相关文章:
- 为什么“;未定义的“;在JavaScript中结束循环
- 要求未定义JS回调参数
- 如何检查管道中未定义的项目
- TypeError:无法读取属性'推'未定义的JavaScript
- $window.ga在AngularJS事件中未定义
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 无法获取属性'selectedIndex'的未定义引用或null引用
- 如何消除代码中的未定义和其他问题
- 未捕获的ReferenceError:$未定义
- 试图将onChange函数作为道具传递给GrandChlidren,结果是TypeError:这是未定义的
- 未捕获的类型错误:无法读取属性'道具'reactJS中未定义的
- 无法读取属性'道具'React容器中自定义onTouch函数中未定义的
- Redux:渲染时未定义道具
- React教程:TypeError:无法读取属性'道具'的未定义
- TypeError:无法设置属性'道具'的未定义
- Reactjs:作为道具访问时未定义的键
- 为什么在使用redux和react.js时我的道具“未定义”
- React Render调用两次,第二次未定义道具
- 当试图作为道具传递时,React状态变量意外未定义