我正在尝试做教程:https://facebook.github.io/react/docs/tutorial.html 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 的方式实现它。能够到达这一点,但现在出现错误:
TypeError: this.props is undefined
无法弄清楚问题所在。知道为什么吗?谢谢
使用时React https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding and ES6 类 https://facebook.github.io/react/docs/reusable-components.html#es6-classesReact 不会自动绑定在类中声明的函数。
因此要么使用this.loadCommentsFromServer.bind(this)
或使用箭头函数
loadCommentsFromServer = () => {}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)