获取TypeError:在ReactJs上未定义this.props [英] Getting TypeError: this.props is undefined on ReactJs
问题描述
我正在尝试做教程: https://facebook.github.io/ react / docs / tutorial.html
import React, { PropTypes } from 'react';
import classnames from 'classnames';
import styles from './CommentBox.css';
import withStyles from '../../decorators/withStyles';
import Link from '../../utils/Link';
import $ from 'jquery';
@withStyles(styles)
class CommentBox extends React.Component {
constructor() {
super();
this.state = {data: []};
}
loadCommentsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
})
}
componentDidMount() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
}
render() {
let url="/public/comments.json"
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
}
class CommentList extends React.Component {
render() {
let data = this.props.data
var commentNodes = data.map(function (comment) {
return (
<Comment author={comment.author}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
};
class Comment extends React.Component {
render() {
return(
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.children}
</div>
);
}
}
class CommentForm extends React.Component {
render() {
return (
<div className="commentForm">
Hello, world! I am a CommentForm.
</div>
);
}
};
export default CommentBox;
然而,本教程有点过时,我使用的是带有ES6语法的React 0.14-rc1。我已尽力遵循教程并以0.14方式实现它。能够达到这一点,但现在得到错误:
However, the tutorial is a bit outdated and I am using React 0.14-rc1 with ES6 syntax. I have tried my best to follow the tutorial and implementing it the 0.14 way. Was able to get to this point but now getting the error:
TypeError: this.props is undefined
无法找出问题所在。知道为什么吗?谢谢
Could not figure out the issue. Any idea why? Thanks
推荐答案
使用 React 和 ES6类 React不会自动绑定在你的类中声明的函数。
When using React and ES6 classes React won't auto bind functions that is declared on your class.
因此使用 this.loadCommentsFromServer.bind(this)
或使用箭头函数
Therefore either use this.loadCommentsFromServer.bind(this)
or use arrow functions
loadCommentsFromServer = ()=> {}
这篇关于获取TypeError:在ReactJs上未定义this.props的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!