【问题标题】:Callback not working after deleting comment. REACT删除评论后回调不起作用。反应
【发布时间】:2017-07-04 17:00:21
【问题描述】:

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

我将发布下面的代码来帮助解决这个问题。

显示页面:

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);
    }
  });
}

【问题讨论】:

  • 您确定正在调用then(() =&gt; cb()) 吗?

标签: javascript node.js mongodb reactjs express


【解决方案1】:

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

你可以尝试在 dispatch action 之后调用callback

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

【讨论】:

  • 两种工作方式我只是路由到同一个页面。我的问题是如何让评论在删除时消失?我必须刷新才能让它不显示
  • 没关系,这是一个不同的问题,后端只是更新,而不是状态未更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多