technology-blog icon indicating copy to clipboard operation
technology-blog copied to clipboard

react项目中,constructor(){ this.target = this.func.bind(this); },JSX里onChange={this.target}的写法,为什么要比非bind的func = () => {}的写法效率高 请解释其中的原理

Open airuikun opened this issue 5 years ago • 12 comments

react项目中,constructor(){ this.target = this.func.bind(this); },JSX里onChange={this.target}的写法,为什么要比非bind的func = () => {}的写法效率高 请解释其中的原理

这题考察了函数在内存块占用执行和调度等,和对bind的深层理解。

airuikun avatar May 12 '19 16:05 airuikun

bind之后锁定了上下文,不用向上查找

yuanxiaowa avatar May 13 '19 01:05 yuanxiaowa

免去了向上查找执行上下文的过程

bfrontend avatar May 13 '19 02:05 bfrontend

repost,get it~

JserJser avatar May 15 '19 07:05 JserJser

多了一次函数声明 。

webkonglong avatar Jun 02 '19 05:06 webkonglong

箭头函数每次render都是新的,this.target一直都是同一个,箭头函数会造成不必要的diff

BoiAbsent avatar Jul 24 '19 10:07 BoiAbsent

箭头函数每次render都是新的,this.target一直都是同一个,箭头函数会造成不必要的diff

react 并不会对属性进行 diff(除了 key 属性) react 的 diff 策略是标签名字(组件名称)和 key 所以并不会造成不必要的 diff

hileix avatar Aug 08 '19 05:08 hileix

箭头函数每次render都是新的,this.target一直都是同一个,箭头函数会造成不必要的diff

react 并不会对属性进行 diff(除了 key 属性) react 的 diff 策略是标签名字(组件名称)和 key 所以并不会造成不必要的 diff

抱歉我描述得不对 是造成不必要的render,导致 PureComponent 或 shouldComponentUpdate() 的优化失效 可以参考这里

BoiAbsent avatar Aug 08 '19 06:08 BoiAbsent

箭头函数每次render都是新的,this.target一直都是同一个,箭头函数会造成不必要的diff

react 并不会对属性进行 diff(除了 key 属性) react 的 diff 策略是标签名字(组件名称)和 key 所以并不会造成不必要的 diff

抱歉我描述得不对 是造成不必要的render,导致 PureComponent 或 shouldComponentUpdate() 的优化失效 可以参考这里

其实你说的没问题。 render 其实就是 diff,是我忽略了 props。 props 属性值(如题所示的便是箭头回调函数)改变了的话,是会导致 PureComponent 的自动优化失效。

hileix avatar Aug 09 '19 01:08 hileix

bind之后锁定了上下文,不用向上查找

请问箭头函数没有锁定吗

bowencool avatar Aug 20 '19 05:08 bowencool

箭头函数每次render都是新的,this.target一直都是同一个,箭头函数会造成不必要的diff

题意应该是这个意思吧

class A {
  foo = () => {};
}
class B {
  constructor(){ this.foo = this.foo.bind(this); }
  foo() {}
}

bowencool avatar Aug 20 '19 05:08 bowencool

箭头函数是实例上的方法,而函数声明是在原型上的方法。

bowencool avatar Aug 20 '19 05:08 bowencool

constructor() { this.target = () => { } } 这样跟上文第一种哪个效率高呢

ruoruoji avatar Mar 06 '20 10:03 ruoruoji