javascript - 在 ngFor 中使用过滤器函数有好处吗?

标签 javascript angular

我在这里找到了一些答案,人们建议使用与此类似的一行代码:

<div *ngFor="let x of filter(myArray)">

但是,filter(myArray) 一直运行

我发现像下面这样保留 2 个数组会更有效率。

<div *ngFor="let x of filteredArray">

代码

let fullArray = [1,2,3,4,5,6]
let filteredArray = []

onFilterEvent() {
    filteredArray = fullArray.filter(x => /* filtering logic */)
}

这里的缺点是我不断地重写 filteredArray 的内容。但是,它仅在需要过滤逻辑时才运行,而不是一直运行。

有没有理由使用第一种方法?它仍在做同样的工作,但它会一遍又一遍地做。

最佳答案

出于性能的原因,Angular 建议将过滤和排序逻辑移至组件本身。您应该在组件内部进行过滤,而不是不断运行管道或函数:

The Angular team and many experienced Angular developers strongly recommend moving filtering and sorting logic into the component itself. The component can expose a filteredHeroes or sortedHeroes property and take control over when and how often to execute the supporting logic. Any capabilities that you would have put in a pipe and shared across the app can be written in a filtering/sorting service and injected into the component.

https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

关于javascript - 在 ngFor 中使用过滤器函数有好处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45535717/

相关文章:

javascript - 它是浏览器对javascript的一种虚拟机吗?

javascript - 为什么 node.js `fs.existsSync` 在用 promise 包装时不能正常工作?

php - 从 div 到 textarea 的内容

angular - Angular 2的转译过程

Angular - 如何获取嵌套组件引用?

angular - 如何更改 Angular Mat 表格头行背景颜色、字体等

node.js - 我如何单独运行同一个应用程序

javascript - 如何使用书签(如 Google Reader 中的注释)在任何网站的页面中显示表单?

JavaScript 如何从作为参数传递的对象访问变量?

javascript - 扩展面板组标题和迭代子对象