【问题标题】:Making UI update when comments are deleted.删除评论时更新 UI。
【发布时间】:2018-12-05 05:38:20
【问题描述】:

我有一个带有 cmets 的 react post 组件。

cmets 分布在三个具有类似结构的组件上

PaginatedComments (contains array of comments as state) --> Comments (which is a higher order component --> SingleComment (which is each individual comment)

现在我已经在我的 PaginatedComments 中创建了一个处理程序 从状态中删除 cmets

deleteCommentHandler = (indexToDelete) =>{
    console.log(this.state.comments)
    this.state.comments.splice(indexToDelete, 1)
    console.log(this.state.comments)
    }

使用 console.log 我成功地检查了评论是否被删除

然后我将函数作为 prop 传递,并将 cmets 作为状态传递:

<Comments comments={this.state.comments} clicked={this.deleteCommentHandler} />}

在我的高阶组件中,该方法通过

向下传递

高阶组件

  <ul className="comments">
  {this.props.comments.map(comment =>
    <SingleComment key={comment.id} comment={comment} clicked={this.props.deleteCommentHandler} {...this.props}/>
  )}
</ul>

)

然后我为每个评论调用该函数,并带有一个按钮。我还提出了一个服务器请求,在后端将其删除。

deleteCommentHandler = (id) =>{
  console.log(id);
  this.setState({
    loading: true
  })

  this.commentMapper.deletePostComments(id).then(res =>{ // deletes comment in backend
    this.setState({loading: false})
  });
  let indexToDelete = this.props.comments.findIndex((comment) =>{
    return comment.id === id;
  });
 this.props.clicked(indexToDelete)
 console.log('we are here')

但是,每当我单击按钮时,UI 都不会呈现?

有点奇怪的是,在我的 deleteCommenthandler 中使用控制台登录时,它最初会注销一个空对象

(来自 Chrome 开发工具)

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    问题出在这部分代码

    deleteCommentHandler = (indexToDelete) =>{
        console.log(this.state.comments)
        this.state.comments.splice(indexToDelete, 1)
        console.log(this.state.commentdirectly
    

    您正在直接更改状态的详细信息。

    切勿直接更改状态详细信息,否则更改将不会反映在 DOM 中,因为从未调用过 render。

    始终使用this.setState({..}) 更新您的状态值

    您可以在您的deleteCommentHandler 中进行类似的更改。

    注意:仅供参考如何进行更改,代码可能有效也可能无效

    deleteCommentHandler = (indexToDelete) =>{
         console.log(this.state.comments)
         var currComments = this.state.comments;
         currComments.splice(indexToDelete, 1);
         this.setState({comments: currComments})
        console.log(this.state.comments)
    }
    

    进行此更改后尝试。

    【讨论】:

      【解决方案2】:

      你在这里改变状态而不使用 setState():

      this.state.comments.splice(indexToDelete, 1)
      

      splice 会改变 cmets 的内容。所以状态永远不会被 this.setState 改变。 render() 不会被调用。

      【讨论】:

        猜你喜欢
        • 2021-02-26
        • 1970-01-01
        • 1970-01-01
        • 2021-05-01
        • 1970-01-01
        • 2012-03-13
        • 2011-12-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多