【发布时间】:2016-03-31 15:26:05
【问题描述】:
在学习 React 和 ES6 的过程中,我学习了官方教程并尝试使其与 ES6 兼容。但是在执行 Ajax 请求时,出现以下错误:
CommentBox.js:23 Uncaught TypeError: Cannot read property 'url' of undefined
这是我的评论框文件/代码:
import React from 'react';
import CommentList from './CommentList.js';
import CommentForm from './CommentForm.js';
export default class CommentBox extends React.Component {
constructor(props) {
super(props);
console.log(this.props)
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)
});
}
handleCommentSubmit(comment) {
let comments = this.state.data;
// Optimistically set id on the new comment.
// It will be replaced by an id generated by the server.
// In a production you would have a more robust system in place.
comment.id = Date.now();
let newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
this.setState({data: comments});
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}
componentDidMount() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
}
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
}
错误发生在loadCommentsFromServer;似乎不知道this.props 是什么。我认为这是一个 this reference 问题,并找到了 similar question 建议使用新的 ES6 箭头来解决问题。然后我尝试了:loadCommentsFromServer = () => {},但是 Browserify 抱怨并且没有构建。
【问题讨论】:
-
参见建议副本中的“常见问题:使用对象方法作为回调/事件处理程序”。
-
需要手动绑定。 ES6 类不会自动绑定
标签: reactjs ecmascript-6