JSX 属性中的 Lambda 是反模式吗? [英] Are Lambda in JSX Attributes an anti-pattern?

查看:35
本文介绍了JSX 属性中的 Lambda 是反模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天开始使用新的 linter (tslint-react),它给了我以下警告:

I started using a new linter today (tslint-react) and it is giving me the following warning:

由于影响渲染性能,JSX 属性中禁止使用 Lambda"

"Lambdas are forbidden in JSX attributes due to their rendering performance impact"

我知道这会导致每次渲染都会创建一个新函数.并且它可能会触发不需要的重新渲染,因为子组件会认为它的 props 已经改变.

I get that this causes the a new function to be created with each render. And that it could trigger unneeded re-renders because the child component will think it's props have changed.

但我的问题是,如何在循环内将参数传递给事件处理程序:

But my question is this, how else can one pass parameters to an event handler inside a loop:

customers.map( c => <Btn onClick={ () => this.deleteCust(c.id) } /> );

推荐答案

绝对不是反模式.

Lambda(箭头函数)对渲染性能没有影响.

Lambdas (arrow functions) have no impact on rendering performance.

唯一有影响的是shouldComponentUpdate 的实现.默认情况下,此函数返回 true,这意味着始终呈现组件.这意味着即使 props 没有改变,组件仍然会再次渲染.这是默认行为.

The only thing that has an impact is the implementation of shouldComponentUpdate. This function returns true by default, meaning that the component is always rendered. That means that even if the props don't change, the component is still rendered again. And that's the default behavior.

如果不实现shouldComponentUpdate,将箭头函数更改为绑定方法不会提高性能.

Changing arrow function to a bound method won't improve the performance if you don't implement shouldComponentUpdate.

确实,不使用箭头函数可以简化 shouldComponentUpdate 的实现,它们不应该与 PureComponent 一起使用,但它们不是反模式.它们可以简化许多模式,例如向函数添加附加参数时(例如,您在示例中执行的操作).

It's true that not using arrow functions can simplify the implementation of shouldComponentUpdate and they should not be used with PureComponent but they are not an antipattern. They can simplify many patterns, e.g. when adding an additional parameter to function (e.g. what you are doing in your example).

另请注意,React 具有无状态组件,它们甚至无法实现 shouldComponentUpdate,因此它们总是被渲染.

Also note that React has stateless components which cannot even implement shouldComponentUpdate and therefore they are always rendered.

在真正发现性能问题之前不要考虑性能影响.

Don't think about performance impact until you actually find a performance problem.

这篇关于JSX 属性中的 Lambda 是反模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆