javascript - 如何在 Redux reducer 中处理树形实体?

标签 javascript reactjs-flux flux redux

我在思考如何实现一个 reducer ,使其实体可以具有相同类型的子级。

让我们以 Reddit 评论为例:每个评论都可以有子评论,子评论本身也可以有评论等。 为简单起见,评论是 {id, pageId, value, Children} 类型的记录,其中 pageId 是 reddit 页面。

如何围绕它建模 reducer ?我正在考虑让reducer成为评论的map -> id,您可以使用pageId按页面进行过滤。

问题是,例如,当我们想要向嵌套注释添加注释时:我们需要在 map 的根目录上创建记录,然后将其 id 添加到父子属性中。要显示我们需要获取所有评论的所有评论,请过滤顶部的评论(例如,它们将作为有序列表保留在页面缩减器中),然后迭代它们,在以下情况下从评论对象中获取我们遇到使用递归的 child 。

有比这更好的方法还是有缺陷?

最佳答案

官方的解决方案是使用normalizr保持这样的状态:

{
  comments: {
    1: {
      id: 1,
      children: [2, 3]
    },
    2: {
      id: 2,
      children: []
    },
    3: {
      id: 3,
      children: [42]
    },
    ...
  }
}

您说得对,您需要connect() Comment 组件,以便每个组件都可以递归查询它感兴趣的children来自 Redux 商店:

class Comment extends Component {
  static propTypes = {
    comment: PropTypes.object.isRequired,
    childComments: PropTypes.arrayOf(PropTypes.object.isRequired).isRequired
  },

  render() {
    return (
      <div>
        {this.props.comment.text}
        {this.props.childComments.map(child => <Comment key={child.id} comment={child} />)}
      </div> 
    );
  }
}

function mapStateToProps(state, ownProps) {
  return {
    childComments: ownProps.comment.children.map(id => state.comments[id])
  };
}

Comment = connect(mapStateToProps)(Comment);
export default Comment;

我们认为这是一个很好的妥协。您将 comment 作为 prop 传递,但组件从存储中检索 childrenComments

关于javascript - 如何在 Redux reducer 中处理树形实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798193/

相关文章:

javascript - 为什么在 Facebook Flux 上使用 Redux?

javascript - 与 `forEach` 使用相关的异步/等待竞争条件?

reactjs - 如何为 RelayMutations 触发 Flux 操作

backbone.js - Flux+React 与 Backbone+React

javascript - ReactJS 嵌套列表 (flux)

javascript - 要求另一家商店中的商店不起作用

javascript - React - 刷新时总是进入初始页面

基于 Javascript/Node.js 的 Fabric 等价物?

javascript - 当我尝试引用另一个模式的对象时,为什么 mongoose ref 对我不起作用?

javascript - 如何展示具体的JSON数据?