Vin*_*t P 22 javascript flux reactjs-flux redux
我有点想到如何实现一个reducer,其实体可以有相同类型的子.
让我们以reddit注释为例:每个注释都可以有子注释,可以自己注释等等.为了简化原因,注释是类型的记录{id, pageId, value, children}
,pageId
是reddit页面.
如何为减速机建模?我正在考虑让reducer成为一个map - > id的注释,你可以使用它来逐页过滤pageId
.
问题是,例如当我们想要为嵌套的注释添加注释时:我们需要在地图的根上创建记录,然后在父子属性中添加其id.要显示我们需要获取所有这些注释的所有注释,请过滤掉我们在顶部的那些注释(例如,将它们作为orderedList保存在页面reducer中)然后迭代它们,从注释对象获取时我们遇到使用递归的孩子.
有没有比这更好的方法或有缺陷?
Dan*_*mov 36
官方解决方案是使用normalizr来保持你的状态:
{
comments: {
1: {
id: 1,
children: [2, 3]
},
2: {
id: 2,
children: []
},
3: {
id: 3,
children: [42]
},
...
}
}
Run Code Online (Sandbox Code Playgroud)
你说得对,你需要connect()
的Comment
组件,这样每个人都可以递归查询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;
Run Code Online (Sandbox Code Playgroud)
我们认为这是一个很好的妥协.您comment
作为道具传递,但组件childrenComments
从商店检索.
归档时间: |
|
查看次数: |
9614 次 |
最近记录: |