删除评论后回调无效。 REACT

时间:2017-07-04 17:00:22

标签: javascript node.js mongodb reactjs express

我收到评论删除就好了,但由于某种原因,没有调用回调。我认为可能会将多个参数传递给函数,但我不确定。

我将发布以下代码以帮助解决此问题。

显示页面

renderCommentsButtons(comment) {
    const { post, user, auth } = this.props;

    if(!user) {
      return (<div></div>);
    }

    if(auth) {
      if(user._id === comment.author.id) {
        return (
          <div>
            <button
              onClick={() => this.deleteComment(comment)}
              className="btn btn-xs btn-danger">
              Delete
            </button>
            <Link
              to={`/posts/${post._id}/comments/${comment._id}/edit`}
              className="btn btn-xs btn-warning">
              Edit
            </Link>
          </div>
        )
      }
    }
  }

  renderComments() {
    const { post } = this.props;
    return post.comments.map((comment) => {
      return (
        <li className="list-group-item" key={comment._id}>
          <div>
            {comment.text} : {comment.author.email}
          </div>
          {this.renderCommentsButtons(comment)}
        </li>
      );
    });
  }

  deleteComment(comment) {
    const {id} = this.props.match.params;
    const {user, post, auth} = this.props;

    if(!user) {
      return (<div></div>);
    }

    if(auth) {
      if(user._id === comment.author.id){
        console.log('comment_id:', comment._id, 'post_id:', post._id);
        this.props.deleteComments(post._id, comment._id, () => {
          this.props.history.push(`/posts/${post._id}`);
        });
      }
    }
  }

动作:

export function deleteComments(post_id, comment_id, cb) {
  return function(dispatch) {
    console.log('comment_id:', comment_id, 'post_id:', post_id);
    axios.delete(`${ROOT_URL}/${post_id}/comments/${comment_id}`)
      .then(() => {
        dispatch({
          type: DELETE_COMMENTS,
          payload: comment_id
        });
      })
      .then(() => cb())
      .catch((error) => {
        console.log(error);
      });
  }
}

后端:

exports.deleteComment = function(req, res, next) {
  const query = {_id: req.params.comment_id};

  Comments.remove(query, function(err, comments) {
    if(err) {
      return next(err);
    } else {
      res.json(comments);
    }
  });
}

1 个答案:

答案 0 :(得分:0)

.then(() => { dispatch(/* action */) } )没有返回任何承诺,这就是.then(() => cb())未执行的原因。

您可以在调度操作后尝试调用callback

axios.delete(`${ROOT_URL}/${post_id}/comments/${comment_id}`)
  .then(() => {
    dispatch({ /* action */})
    cb();
  })
  .catch((error) => {
    console.log(error);
  });