我有点陷入思考如何实现一个减速器,其中它的实体可以有相同类型的子级。
让我们以 Reddit 评论为例:每个评论都可以有子评论,子评论本身也可以有评论等。
为了简单起见,评论是类型的记录{id, pageId, value, children}
, with pageId
是 reddit 页面。
如何围绕它建立减速器模型?我正在考虑让减速器成为评论的地图 -> id,您可以使用以下命令按页面进行过滤pageId
.
问题是,例如,当我们想要向嵌套注释添加注释时:我们需要在地图的根目录上创建记录,然后将其 id 添加到父子属性中。要显示我们需要获取所有评论的所有评论,请过滤顶部的评论(例如,它们将作为有序列表保留在页面缩减器中),然后迭代它们,在以下情况下从评论对象中获取我们遇到使用递归的孩子。
有比这更好的方法还是有缺陷?
官方的解决方案是使用归一化 https://github.com/gaearon/normalizr保持这样的状态:
{
comments: {
1: {
id: 1,
children: [2, 3]
},
2: {
id: 2,
children: []
},
3: {
id: 3,
children: [42]
},
...
}
}
你是对的,你需要connect()
the 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
作为道具,但组件检索childrenComments
从商店。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)