ReactJS - 附加POST响应

时间:2017-11-03 01:37:17

标签: reactjs express

我对ReactJS很新,我正试图找出最好的方法来追加并呈现我最近创建的记录,而无需刷新我的页面。目前我的溃败有一个重定向,这是有道理的,为什么触发的帖子通过postComment()刷新页面,但我很好奇我应该如何1)修改我成功的POST路由发送一个JSON消息反应使用而不刷新2)用新创建的评论更新我的评论部分。我应该将Comments组件转换为处理更改的状态吗?

(注意:注释组件是一个模块,其中Comments填充了从单独文件传递的数组)

评论逻辑:

import React from 'react';
import fetch from 'node-fetch';

//Record Comment - Comment
const Comment = props => {
    return (
        <div className="row">
            <div className="col-md-12">
                <h5>{props.user_id}</h5>
                <h4>{props.comment}</h4>
                <h3>{props.app_user.fullNameSlug}</h3>
            </div>
        </div>
    )
} 

//Record Comment - Comment Form
class CommentForm extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            value: ''
        };
        this.onChange = this.onChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    postComment(comment) {
        fetch('http://localhost:3000/record/:recordId/comment', { method: 'POST', body: comment})
            .then(res => {
                return res.json();
            })  
            .then(data => {
                console.log(data);
            }) 
            .catch(err => {
                console.log(err);
            });
    }

    onChange(e){
        this.setState({
            value: e.target.value
        });
    }

    handleSubmit(e){
        alert('This is the submit ' + this.state.value);
        postComment();
        e.preventDefault();

    }

    render(){
        return (
            <div className="record-comment__form">
                <div className="row">
                    <div className="col-md-12">
                        <label>Comment:</label>
                    </div>
                </div>
                <div className="row">
                        <form action={"/app/record/" + this.props.recordId + "/comment"} method="post" onSubmit={this.handleSubmit}>
                            <input type="hidden" name="_csrf" value={this.props.csrf}/>
                            <div className="col-md-9">
                                <textarea name="comment" className="record-comment__form-text-area" onChange={e => this.setState({ value: e.target.value })} value={this.state.value}></textarea>
                            </div>
                            <div className="col-md-3">
                                <button type="submit" className="record-comment__form-button" disabled={!this.state.value}>Comment</button>
                            </div>
                        </form>
                </div>
            </div>
        )
    }
}

//Record Comment - Container
export default class Comments extends React.Component {
    render() {
        return (
            <div className="record-comment-container">
                <CommentForm recordId={this.props.recordId} csrf={this.props.csrf}/>
                { this.props.record_comments.map((comment, i) => 
                    <Comment {...comment} key={this.props.recordCommentId}/>
                )}
            </div>
        );
    }
}

ExpressJS路线:

//POST /record/:recordId/comment
exports.create = function(req, res){
    var hashids = new Hashids('record', 10);
    var decodedHash = hashids.decode(req.params.recordId);
    var annotationId = decodedHash[0];

    models.RecordComment.create({
        comment: req.body.comment,
        commentId: commentId,
        userId: req.user.userId
    }).then(function(){
        req.flash('success', 'Comment was successfully created');
        res.redirect(req.get('referer'));
    });
};

1 个答案:

答案 0 :(得分:1)

您必须在postComment()方法和州内进行一些更改。喜欢这个

   //Record Comment - Comment Form
    class CommentForm extends React.Component {
        constructor(props){
            super(props);
            this.state = {
                value: '',
                comments:[]
            };
            this.onChange = this.onChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
        }

        postComment(comment) {
            fetch('http://localhost:3000/record/:recordId/comment', { method: 'POST', body: comment})
                .then(res => {
                    return res.json();
                })  
                .then(data => {
                    console.log(data);
                    let oldComments = this.state.comments;
                    this.setState({comments:oldComments.concat(data)});
                }) 
                .catch(err => {
                    console.log(err);
                });
        }
   onChange(e){
        this.setState({
            value: e.target.value
        });
    }

    handleSubmit(e){
        alert('This is the submit ' + this.state.value);
        this.postComment();
        e.preventDefault();

    }

在路线中,您必须发送/检索已保存的对象。因此尝试这样的事情

//POST /record/:recordId/comment
exports.create = function(req, res){
    var hashids = new Hashids('record', 10);
    var decodedHash = hashids.decode(req.params.recordId);
    var annotationId = decodedHash[0];

    let reccoment = new RecordComment({
        comment: req.body.comment,
        commentId: commentId,
        userId: req.user.userId
    });
    reccoment.save(function(err,comment){
              res.json(comment);
    });
};