这个官方的解决方案是使用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
作为道具,但组件从商店检索childrenComments
。
我认为你可以尝试normalizr:https://github.com/gaearon/normalizr自己没有使用它,所以我不知道它是否会帮助你在你的情况。 – Simon
我知道normalizr,我更想知道是否有一个“接受”的解决方案,如何在组件中处理它。 除非你连接()每一条评论,否则每次更改都需要对normalizr做相反的处理,即使你连接的时候看起来有点像一团糟 –