我正在使用React和Node.js创建一个短篇小说/博客网站。我有一个Node路由将新故事发布到我的mongo数据库。该路由与superagent-cli一起创建一个新故事并且它通过了所有测试,因此我知道问题不在于路由本身。
表单在页面上呈现正常,但无论是按Enter键还是单击,它都不会将数据提交到数据库。
以下是表单组件的外观:
'use strict';
var React = require('react');
module.exports = React.createClass({
submitHandler: function (event) {
event.preventDefault();
var author = React.findDOMNode(this.refs.author).value.trim();
var categories = React.findDOMNode(this.refs.categories).value.trim();
var storyTitle = React.findDOMNode(this.refs.storyTitle).value.trim();
var storyText = React.findDOMNode(this.refs.storyText).value.trim();
this.props.submit({author: author, categories: categories, storyTitle: storyTitle, storyText: storyText});
},
render: function () {
return(
<form onSubmit={this.submitHandler}>
<input type="checkbox" ref="categories" value="fiction">Fiction</input>
<input type="checkbox" ref="categories" value="CreepyPasta">CreepyPasta</input>
<input type="checkbox" ref="categories" value="Horror">Horror</input>
<input type="checkbox" ref="categories" value="Monsters">Monsters</input>
<br />
<input ref="storyTitle" placeholder="Title" />
<br />
<input ref="author" placeholder="Author" />
<br />
<input ref="storyText" placeholder="Add your story here"/>
<br />
<input type="submit" value="Save Story"></input>
</form>
)
}
});
这是表单的视图:
'use strict';
var React = require('react');
var StoryForm = require('../add-story-form.jsx');
var request = require('superagent');
module.exports = React.createClass({
getInitialState: function () {
return {title: 'Add Your Own Story'};
},
submit: function (storyObj) {
request
.post('/api/stories')
.send(storyObj)
.end(function (err, res) {
if (err) {
return console.log(err);
}
}.bind(this));
},
render: function () {
return (
<main>
<h1>{this.state.title}</h1>
<StoryForm submit={this.submit}/>
</main>
)
}
});
最后,这是我的主要React客户端组件,它执行我的React路由:
'use strict';
var React = require('react');
var Router = require('react-router-component');
var Locations = Router.Locations;
var Location = Router.Location;
var MainPage = require('./components/views/main-page.jsx');
var CategoryPage = require('./components/views/category-page.jsx');
var FormPage = require('./components/views/story-form-page.jsx');
var App = React.createClass({
render: function () {
return (
<Locations hash>
<Location path="/" handler={MainPage} />
<Location path="/stories/:category" handler={CategoryPage} />
<Location path="/addstory" handler={FormPage} />
</Locations>
)
}
})
React.render(<App />, document.body)
如果有更多信息可以提供帮助,请与我们联系。您可以在my github repo
上查看此分支上的完整项目答案 0 :(得分:2)
submit: function (storyObj) {
request
.post('/api/stories')
.send(storyObj)
.end(function (err, res) {
if (err) {
return console.log(err);
}
}.bind(this));
},
使用jQuery ajax解决这个问题可能很简单:
submit: function (storyObj) {
$.post('/api/stories',storyObj, function () {
console.log('success')
})
},