我现在想要做什么,我已经走了,但是当它们被发布到页面时,每个评论都会添加一个时间戳。任何人都可以帮助我吗?
这是我到目前为止的代码,它是主要的JS文件。
var CommentList = React.createClass({
render: function(){
var commentNodes = this.props.data.map(function(comment) {
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var CommentForm = React.createClass({
getInitialState: function(){
return {author: '', text: ''};
},
handleAuthorChange: function(e){
this.setState({author: e.target.value});
},
handleTextChange: function(e){
this.setState({text: e.target.value});
},
handleSubmit: function(e){
e.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if(!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
this.setState({author: '', text: ''});
},
render: function(){
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your Name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input type="text" placeholder="Say Something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="post" />
</form>
);
}
});
var Comment = React.createClass({
render: function(){
return(
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.children}
</div>
);
}
});
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)
});
},
handleCommentSubmit: function(comment){
var comments = this.state.data;
comment.Id = Date.now();
var 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)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function(){
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function(){
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')
);
这是server.js文件。
/**
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var COMMENTS_FILE = path.join(__dirname, 'comments.json');
app.set('port', (process.env.PORT || 3000));
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// Additional middleware which will set headers that we need on each request.
app.use(function(req, res, next) {
// Set permissive CORS header - this allows this server to be used only as
// an API server in conjunction with something like webpack-dev-server.
res.setHeader('Access-Control-Allow-Origin', '*');
// Disable caching so we'll always get the latest comments.
res.setHeader('Cache-Control', 'no-cache');
next();
});
app.get('/api/comments', function(req, res) {
fs.readFile(COMMENTS_FILE, function(err, data) {
if (err) {
console.error(err);
process.exit(1);
}
res.json(JSON.parse(data));
});
});
app.post('/api/comments', function(req, res) {
fs.readFile(COMMENTS_FILE, function(err, data) {
if (err) {
console.error(err);
process.exit(1);
}
var comments = JSON.parse(data);
// NOTE: In a real implementation, we would likely rely on a database or
// some other approach (e.g. UUIDs) to ensure a globally unique id. We'll
// treat Date.now() as unique-enough for our purposes.
var newComment = {
id: Date.now(),
author: req.body.author,
text: req.body.text,
};
comments.push(newComment);
fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null, 4), function(err) {
if (err) {
console.error(err);
process.exit(1);
}
res.json(comments);
});
});
});
app.listen(app.get('port'), function() {
console.log('Server started: http://localhost:' + app.get('port') + '/');
});
答案 0 :(得分:1)
每当您保存评论时,您都需要为保存的数据添加时间戳。在server.js中,我们可以修改comment-save处理程序以添加时间戳:
app.post('/api/comments', function(req, res) {
fs.readFile(COMMENTS_FILE, function(err, data) {
if (err) {
console.error(err);
process.exit(1);
}
var comments = JSON.parse(data);
// NOTE: In a real implementation, we would likely rely on a database or
// some other approach (e.g. UUIDs) to ensure a globally unique id. We'll
// treat Date.now() as unique-enough for our purposes.
var newComment = {
id: Date.now(),
author: req.body.author,
text: req.body.text,
timestamp: new Date() // Add timestamp to saved comment
};
comments.push(newComment);
fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null, 4), function(err) {
if (err) {
console.error(err);
process.exit(1);
}
res.json(comments);
});
});
});
好的,现在我们在保存评论时保存时间戳。我们现在需要更新我们的UI以显示这些数据:
var Comment = React.createClass({
render: function(){
return(
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.children}
<span>Created on: {this.props.timestamp}</span>
</div>
);
}
});
我们的评论组件现在期望将时间戳属性作为道具传递。我们需要更新我们的CommentList组件来传递这些数据:
var CommentList = React.createClass({
render: function(){
var commentNodes = this.props.data.map(function(comment) {
return (
<Comment author={comment.author}
key={comment.id}
timestamp={comment.timestamp}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
现在我们将显示每个已保存评论的时间戳!如果您想格式化时间戳,我建议您使用日期帮助程序库,例如:http://momentjs.com/