ReactCollect
ReactCollect copied to clipboard
关于componentWillReceiveProps 和 shouldComponentUpdate
问题:
- 这两者的功能是不是有部分重叠
- 怎么样区分使用者两者,什么时候用什么
参考资料:React Component Lifecycle 参考资料:组件的详细说明和生命周期 参考资料:gitbook: Updating and componentWillReceiveProps()
做了一个测试
// ...
shouldComponentUpdate(nextProps, nextState){
console.log('shouldComponentUpdate');
return true;
}
componentWillReceiveProps(nextProps){
console.log('componentWillReceiveProps');
return false;
}
render(){
console.log('render');
}
- 执行顺序是componentWillReceiveProps =>shouldComponentUpdate =>render
- 无论componentWillReceiveProps返回什么,true还是false, 都会往下执行shouldComponentUpdate
- 如果shouldComponentUpdate返回true, 则会继续执行render; 如果返回false, 则不会继续执行render
补充:
- 在componentWillReceiveProps中调用 this.setState() 将不会引起第二次渲染(即不会再次调用render)
- 那么componentWillReceiveProps的作用一般是为了通过props属性更新state的值,并且是在render之前更新,并且这次更新不会触发新的渲染
- shouldComponentUpdate的作用就是阻止不必要的渲染,可以在函数内部直接return false来终止一次setState
very good jobs
@Carrie999 找前端工作吗,坐标杭州
你解决了我的疑惑,谢谢
@Carrie999 找前端工作吗,坐标杭州
坐标北京,寻找新坑中
very good jobs
Good