React内部方法绑定this的另一种可能性。

#1

总所周知,react里面传递方法到子组件里面会有丢失this的风险。具体的解决方法这里不说了,网上都可以查到几种好用方法。
最近在优化直接使用bind方法来绑定的手段。

<div onClick={ this.func.bind(this) }></div>
// 或者简写成
<div onClick={ this::this.func) }></div>

这种做法,会导致每次进入render函数。bind都会生成一个新的方法,造成子组件的更新,被认为是不好的解决办法。
所以我想到,如果bind方法被重复调用时,都会返回同一个方法(把方法缓存起来),那么就可以解决这个问题了。
于是把原型上的bind方法改造了一下:

Function.prototype.bind = function (context, ...args) {
  const self = this
  if (args.length) {
    return function (...innerArgs) {
      return self.apply(context, args.concat(innerArgs))
    }
  }
  if (!this.bindList) this.bindList = new Map()
  if (!this.bindList.has(context)) {
    this.bindList.set(context,
      function (...innerArgs) {
        return self.apply(context, innerArgs)
      }
    )
  }
  return this.bindList.get(context)
}

不知道会不会有未知的风险。

1 Like
#2

箭头函数不行吗

#3

熟练使用Map

#4

箭头函数不会定义在原型上,不是所有实例共有,每一个实例都会生成新的方法。架构上来说,太挫了。