当前位置: 移动技术网 > IT编程>开发语言>JavaScript > react实现pure render时bind(this)隐患需注意!

react实现pure render时bind(this)隐患需注意!

2019年03月22日  | 移动技术网IT编程  | 我要评论

pure render 我就不多说了,附上我另一片文章链接

不论你用不用immutable,只要你想达到pure render,下面值得你注意!

一天我和往常一样,开开心心得写着react,用着@purerender,

export default class extends component {
...
 render() {
  const {name,age} =this.state;
  return (
   <div>
    <person name={name} age={age} onclick={this._handleclick.bind(this)}></person>//bug 所在
   </div>
  )
 }
...
}

发现一个问题,对于person这个子组件来说,在父组件re-render的时候,即使person得前后两个props都没改变,它依旧会re-render,即使用immutable.js也不好使。

原来啊,父组件每次render,_handleclick都会执行bind(this) 这样_handleclick的引用每次都会改,所以person前后两次props其实是不一样的。

那怎么办?把bind(this)去掉?不行 还必须得用

真正的答案是 让父组件每次render 不执行bind(this),直接提前在constructor执行好,修改之后

export default class extends component {
 constructor(props){
  super(props)
  this._handleclick=this._handleclick.bind(this)//改成这样
 }
 render() {
  const {name,age} =this.state;
  return (
   <div>
    <person name={name} age={age} onclick={this._handleclick}></person>
   </div>
  )
 }
...
}

参考:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网