gpt4 book ai didi

angular - @ngrx 在递归使用智能组件时从存储中选择特定的状态片段

转载 作者:太空狗 更新时间:2023-10-29 17:08:02 25 4
gpt4 key购买 nike

我是 ngrx 的新手,我遇到了这个小问题,我还没有想出如何解决。

基本上,我有一个 ListComponent,它从 ngrx 存储中呈现一组 ListItemComponent

@Component({ 
...
template: `
<list-item *ngFor="let item of item$ | async" [data]="item">
</list-item>
`
})
export class ListComponent implements OnInit {
item$: Observable<ListItem>;
constructor(private store: Store<ListState>) {}

ngOnInit() {
this.item$ = this.store.select(selectListItems);
}
}

现在,在 ListItemComponent 中,在某些特定情况下,我想呈现另一个 ListComponent,我可以在其中添加项目,但是这不起作用,因为我得到了 超出最大调用堆栈大小 错误。

我的猜测是,如果我错了请纠正我,因为嵌套的 ListComponent 正在访问与根 ListComponent 相同的状态片,它只是试图一遍又一遍地嵌套并渲染相同的列表到无穷大。

那么问题来了,我应该如何编写选择器,以便在状态树中为每个嵌套的 ListComponent 提供正确的入口点?


编辑

这是一个 working stackblitz project ,现在我的应用程序中在 ListItem 中呈现 List 的逻辑是不同的,但问题是一样的。

最佳答案

我认为你是对的:

My guess is, and correct me if I'm wrong, since the nested ListComponent is accessing the same slice of state as the root ListComponent, its just trying to nest and render the same list over and over and over again into infinity.

尝试更新 ListComponent 以接受 ListItemComponent 的组件输入变量。查看工作示例 https://stackblitz.com/edit/angular-ngrx-recursive-components-7mzncj

在该示例中,第 5 个 ListItemComponent 也呈现一个 ListComponent。但是,当单击第 5 个 ListItemComponent 上的“将元素添加到列表”按钮时,代码仍在将新元素添加到父列表。我猜你会想更新你的逻辑来处理它。不确定您要完成什么。

核心问题是列表是自己生成的。因此,如果一个列表生成另一个列表,就会遇到递归问题。通过使用组件输入变量,您可以阻止列表自行生成并消除递归问题。

更新:

这个答案是我自己得出的,但我只是注意到@FanCheung 在评论中之前提出了这个解决方案的基本内容。

关于angular - @ngrx 在递归使用智能组件时从存储中选择特定的状态片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48126307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com