ReactCollect icon indicating copy to clipboard operation
ReactCollect copied to clipboard

关于componentWillReceiveProps 和 shouldComponentUpdate

Open ckinmind opened this issue 8 years ago • 7 comments

问题:

  1. 这两者的功能是不是有部分重叠
  2. 怎么样区分使用者两者,什么时候用什么

参考资料:React Component Lifecycle 参考资料:组件的详细说明和生命周期 参考资料:gitbook: Updating and componentWillReceiveProps()

ckinmind avatar Jan 16 '17 09:01 ckinmind

做了一个测试

// ...
shouldComponentUpdate(nextProps, nextState){
        console.log('shouldComponentUpdate');
        return true;
    }

    componentWillReceiveProps(nextProps){
        console.log('componentWillReceiveProps');
        return false;
    }

  render(){
      console.log('render');
  }
  1. 执行顺序是componentWillReceiveProps =>shouldComponentUpdate =>render
  2. 无论componentWillReceiveProps返回什么,true还是false, 都会往下执行shouldComponentUpdate
  3. 如果shouldComponentUpdate返回true, 则会继续执行render; 如果返回false, 则不会继续执行render

ckinmind avatar Jan 16 '17 09:01 ckinmind

补充:

  1. 在componentWillReceiveProps中调用 this.setState() 将不会引起第二次渲染(即不会再次调用render)
  2. 那么componentWillReceiveProps的作用一般是为了通过props属性更新state的值,并且是在render之前更新,并且这次更新不会触发新的渲染
  3. shouldComponentUpdate的作用就是阻止不必要的渲染,可以在函数内部直接return false来终止一次setState

ckinmind avatar Jan 16 '17 09:01 ckinmind

very good jobs

Carrie999 avatar May 09 '19 03:05 Carrie999

@Carrie999 找前端工作吗,坐标杭州

ckinmind avatar May 10 '19 03:05 ckinmind

你解决了我的疑惑,谢谢

sy13277072001 avatar May 10 '19 07:05 sy13277072001

@Carrie999 找前端工作吗,坐标杭州

坐标北京,寻找新坑中

Carrie999 avatar May 16 '19 04:05 Carrie999

very good jobs

Good

coderDancer avatar May 29 '19 02:05 coderDancer