我在思考如何实现一个 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/