Skip to content

Commit a7a05ac

Browse files
author
Amir Tocker
committed
Add shouldComponentUpdate to Image. Use setTimeout to wait for the css to load before changing state.
1 parent 9120835 commit a7a05ac

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

src/components/Image/Image.js

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,32 @@ import cloudinary, {Util} from 'cloudinary-core';
33
import CloudinaryComponent from '../CloudinaryComponent';
44
import {debounce, firstDefined, closestAbove} from '../../Util';
55

6+
function compareObjects(o, p) {
7+
let i,
8+
keysO = Object.keys(o).sort(),
9+
keysP = Object.keys(p).sort();
10+
if (keysO.length !== keysP.length) return false;
11+
if (keysO.join('') !== keysP.join('')) return false;
12+
for (i = 0; i < keysO.length; ++i) {
13+
if (o[keysO[i]] instanceof Array) {
14+
if (!(p[keysO[i]] instanceof Array)) return false;
15+
if (p[keysO[i]].sort().join('') !== o[keysO[i]].sort().join('')) return false;
16+
}
17+
else if (o[keysO[i]] instanceof Function) {
18+
if (!(p[keysO[i]] instanceof Function)) return false;
19+
}
20+
else if (o[keysO[i]] instanceof Object) {
21+
if (!(p[keysO[i]] instanceof Object)) return false;
22+
if (o[keysO[i]] === o) {
23+
if (p[keysO[i]] !== p) return false;
24+
} else if (compareObjects(o[keysO[i]], p[keysO[i]]) === false) {
25+
return false;//WARNING: does not deal with circular refs other than ^^
26+
}
27+
}
28+
if (o[keysO[i]] != p[keysO[i]]) return false;//not the same value
29+
}
30+
return true;
31+
}
632

733
export default class Image extends CloudinaryComponent {
834
constructor(props, context) {
@@ -20,6 +46,9 @@ export default class Image extends CloudinaryComponent {
2046
get window() {
2147
return (this.element && this.element.ownerDocument) ? (this.element.ownerDocument.defaultView || window) : window;
2248
}
49+
shouldComponentUpdate( nextProps, nextState){
50+
return !( compareObjects(this.props, nextProps) && compareObjects(this.state, nextState));
51+
}
2352

2453
componentWillReceiveProps(nextProps, nextContext) {
2554
let state = this.prepareState(nextProps, nextContext);
@@ -47,10 +76,12 @@ export default class Image extends CloudinaryComponent {
4776

4877
componentDidMount() {
4978
// now that we have a this.element, we need to calculate the URL
50-
let state = this.prepareState();
51-
if (state.url !== undefined) {
52-
this.setState(state);
53-
}
79+
setTimeout(()=>{
80+
let state = this.prepareState();
81+
if (state.url !== undefined) {
82+
this.setState(state);
83+
}
84+
}, 0);
5485
}
5586

5687
componentWillUnmount() {

0 commit comments

Comments
 (0)