【问题标题】:How to handle tree-shaped entities in Redux reducers?如何处理 Redux reducer 中的树形实体?
【发布时间】:2015-12-24 05:33:12
【问题描述】:

对于如何实现一个reducer,它的实体可以有相同类型的子代,我有点卡住了。

我们以 reddit cmets 为例:每个评论都可以有子 cmets,子 cmets 可以有自己的 cmets 等等。 为简单起见,评论是 {id, pageId, value, children} 类型的记录,pageId 是 reddit 页面。

如何围绕它对减速器进行建模?我正在考虑让 reducer 成为一个 map -> cmets 的 ID,您可以使用 pageId 按页面过滤。

问题在于,例如,当我们想向嵌套的评论添加评论时:我们需要在地图的根目录上创建记录,然后将其 id 添加到父子属性中。要显示我们需要获取所有的所有 cmets,过滤我们在顶部拥有的那些(例如,将作为有序列表保存在页面缩减器中)然后迭代它们,从 cmets 对象中获取我们遇到使用递归的孩子。

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

【问题讨论】:

  • 我想你可以试试 normalizr:github.com/gaearon/normalizr 我自己没用过,所以我不确定它是否对你有帮助。
  • 我知道 normalizr,我更想知道是否有关于如何在组件中处理它的“公认”解决方案。除非你 connect() 每条评论,你都需要在每次更改时执行与 normalizr 相反的操作,即使你确实 connect 看起来有点像一团糟

标签: javascript reactjs-flux flux redux


【解决方案1】:

对此的官方解决方案是使用normalizr 来保持您的状态如下:

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

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

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 传递,但组件从 store 中检索 childrenComments

【讨论】:

【解决方案2】:

您的商店(reducer)结构可能与您想要的视图模型(作为道具传递给组件的视图模型)不同。您可以将所有 cmets 保存在数组中,并通过高级“智能”组件上的 mapStateToProps 中的链接将它们映射到树。您将在 reducer 中获得简单的状态管理,并为组件提供方便的视图模型。

【讨论】:

    猜你喜欢
    • 2017-06-09
    • 1970-01-01
    • 2017-04-03
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2016-05-07
    • 2016-07-26
    相关资源
    最近更新 更多