POST请求后,子组件不会重新呈现父组件

时间:2018-04-28 17:35:58

标签: javascript reactjs

我想在发布新评论时重新呈现评论列表。 我的父组件中的状态设置为 false ,当我从子组件发布注释时,我想要更新该状态。 我可以在POST请求之后调度状态,我可以看到它从false变为true,但它不会重新渲染我的父组件。 到目前为止,只有当我手动刷新页面时,我才能看到新的注释。 我尝试从父级使用回调函数更改状态,但它不起作用。 我相信它可能是一个异步问题,但我不知道如何解决它。

任何想法有什么不对?

PARENT

import React, { Component } from 'react';
import PostCommentForArticle from './PostCommentForArticle'
import axios from 'axios';
import './Comments.css'

class CommentsForArticle extends Component {
  state = {
    isPosted: false
  }
  render() {
    console.log(this.state);
    return (
      <div>
        {this.props.comments.map(comment => {
          return (
            <div class="container" id="container-comments">
              <div class="row">
                <div class="col-sm">
                  {comment.created_by}
                </div>
                <div class="col-sm">
                  {comment.created_at}
                </div>
              </div>
              <div class="row-combody">{comment.body}</div>
              <div class="row-belongsto">{comment.belongs_to}</div>
              <div class="row-votes">{comment.votes}
                <i class="far fa-thumbs-up" id="icon" onClick={() => {
                  this.incrementCommentVote(comment._id)
                  this.setState({ currCommentVote: comment.votes++ })
                }}></i>
                <i class="far fa-thumbs-down" id="icon" onClick={() => {
                  this.decrementCommentVote(comment._id)
                  this.setState({ currCommentVote: comment.votes-- })
                }}></i>
                <i class="far fa-times-circle" id="icon" onClick={() => {
                  this.deleteComment(comment._id)
                  this.setState({ isCommentDeleted: true })
                }}></i>
              </div>
            </div>
          )
        })}
        <PostCommentForArticle
          article={this.props.article}
          func={this.checkIfPosted} />
      </div>
    );
  }
  incrementCommentVote = (id) => {
    axios
      .put(
        `https://ncnewsapp.herokuapp.com/api/comments/${id}?vote=up`,
        "mytoken",
        { headers: { "Content-Type": "text/plain" } }
      )
      .then(result => console.log(result))
      .catch(e => console.log(e));
    //insert error page component
  }
  decrementCommentVote = (id) => {
    axios
      .put(
        `https://ncnewsapp.herokuapp.com/api/comments/${id}?vote=up`,
        "mytoken",
        { headers: { "Content-Type": "text/plain" } }
      )
      .then(result => console.log(result))
      .catch(e => console.log(e));
    //insert error page component
  }
  deleteComment = (data) => {
    axios
      .delete(
        `https://ncnewsapp.herokuapp.com/api/comments/${data}`,
        "mytoken",
        { headers: { "Content-Type": "text/plain" } }
      )
      .then(result => {
        console.log(result);
      })
      .catch(e => console.log(e));
  }

  checkIfPosted = (data) => {
    console.log(data);
    this.setState({ isPosted: data })
  }

}
export default CommentsForArticle;

儿童

import React, { Component } from 'react';
import Articles from './Article';
import axios from 'axios';
import './PostCommentForArticle.css';

class PostCommentForArticle extends Component {
  state = {
    userName: '',
    input: '',
  }
  render() {
    return (
      <div>
        <form id="post-comment-form">
          <div class="form-group">
            <label for="exampleInputEmail1">Username</label>
            <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter username" value={this.state.userName} onChange={this.getUserName} />
            <small id="emailHelp" class="form-text text-muted">Post a comment.</small>
          </div>

          <div class="input-group">
            <textarea class="form-control" aria-label="With textarea" value={this.state.input} onChange={this.getUserInput}></textarea>
            <br />
          </div>
          <button type="button" class="btn btn-primary" onClick={() => this.postComment()}>Submit</button>
        </form>
      </div>
    );
  }

  getUserName = (event) => {
    this.setState({ userName: event.target.value });
  }
  getUserInput = (event) => {
    this.setState({ input: event.target.value });
  }
  postComment = () => {
    let id = this.props.article[0]._id;
    const { userName } = this.state;
    const { input } = this.state
    axios.post(`https://ncnewsapp.herokuapp.com/api/articles/${id}/comments?user=${userName}`,
      {
        "comment": `${input}`,

      })
      .then((data) => {
        this.props.func(true)
      })
  }

}
export default PostCommentForArticle;

1 个答案:

答案 0 :(得分:1)

您只是更新isPosted中的标记CommentsForArticle,但评论是从this.props.comments生成的。您必须确保新评论已添加到comments列表中,当然,从哪里通过,或者您可以考虑将评论添加到CommentsForArticle的状态并添加新评论只是更新旗帜。

当您刷新页面时,您将获得这些新评论,因此它会显示所有这些评论。