[英]ReactJS tutorial- Comment form not posting to local server
I'm trying to set up a local server that hosts a comment submission system (as per the React tutorial ). 我试图建立一个托管评论提交系统的本地服务器(按照React教程 )。 In the CommentForm
class, I want to have the form handle a comment submission, which uses a POST request to modify a local file called comments.json. 在CommentForm
类中,我想让表单处理评论提交,该评论使用POST请求修改名为CommentForm
的本地文件。 This POST request isn't working. 此POST请求无效。 Can anyone figure out why? 谁能找出原因? I have the following code (I have excluded the Comment and CommentList classes to reduce clutter but I will include them if it will be helpful). 我有以下代码(我排除了Comment和CommentList类以减少混乱,但如果有帮助,我将包括它们)。 The console.log line that prints "submitting" is never executed: 永远不会执行打印“ submitting”的console.log行:
var Comment = React.createClass({
// code excluded for brevity
});
var CommentForm = React.createClass({
handleSubmit: function(e) {
console.log("submitting");
e.preventDefault();
var author = this.refs.author.value.trim();
var text = this.refs.text.value.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
this.refs.author.value = '';
this.refs.text.value = '';
return;
},
render: function() {
return (
<form className = "commentForm">
<input type="text" placeholder="Your name" ref="author"/>
<input type="text" placeholder="Say something..." ref="text"/>
<input type="submit" value="Post"/>
</form>
);
}
});
var CommentList = React.createClass({
// code excluded for brevity
});
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.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)
});
},
getInitialState: function() {
return {data: []};
},
handleCommentSubmit: function(comment) {
$.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) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
console.log("rendering box");
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
ReactDOM.render(
<CommentBox url="/api/comments" pollInterval = {2000} />,
document.getElementById('content')
);
您忘记绑定处理程序表单的onSubmit
事件。
<form className="commentForm" onSubmit={this.handleSubmit}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.