【问题标题】:How to update state of parent's parent component in react?如何在反应中更新父级父级组件的状态?
【发布时间】:2015-04-23 11:15:26
【问题描述】:

我正在玩 fb 的评论框教程。假设我添加了删除 cmets 的功能,所以我将在 Comment 组件中添加类似的内容 -

onClick={this.handleCommentDelete}

如何触发commentBox父组件的状态变化,而不是在整个commentList组件中传播回调,然后再到comment组件?

<commentBox>
  <commentList>
    <comment>

【问题讨论】:

  • Flux 架构是这样做的一种方式。在this.handleCommentDelete 中调用ActionCreators.deleteComment 操作。 Dispatcher 将其分派到所有商店。 CommentStore 通过删除评论执行操作并发出更改事件。正在收听CommentStoreCommentBox 使用新的cmets 列表更新自身。
  • 部分问题在于哪个组件实际上“拥有”删除评论的行为。它是基本级别的Comment 组件吗?或者一些容器呢?事件是通过父链传递状态并建立明确所有者的一种非常有效且极其清晰的方式。然后你可以使用 Flux 模式 ...

标签: javascript reactjs reactjs-flux


【解决方案1】:

我正在使用 PubSub 模式在组件之间进行通信。在评论框中:

componentDidMount: function() {
    PubSub.subscribe("COMMENT_DELETED", function( msg, data ){
        console.log( data ); //logs "commentId"
    });
}

在句柄CommentDelete中:

PubSub.publish("COMMENT_DELETED", {commentId: commentId});

对于 PubSub,我正在使用这个库(当然还有其他库):https://www.npmjs.com/package/pubsub-js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 2020-10-05
    • 2017-12-03
    • 1970-01-01
    • 2015-05-21
    • 2017-09-05
    • 1970-01-01
    • 2020-01-23
    相关资源
    最近更新 更多