-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCounter.js
executable file
·58 lines (49 loc) · 1.3 KB
/
Counter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import React, { Component, Fragment } from "react";
import Count from "./Count";
import superExpensiveFunction from "./utils/superExpensiveFunction";
class Counter extends Component {
state = {
count: 0,
timestamp: Date.now()
};
increment = prevState => ({
count: prevState.count + 1
});
decrement = prevState => ({
count: prevState.count - 1
});
handleIncrementClick = () => {
if (this.state.count < 10) {
this.setState(this.increment);
}
};
handleDecrementClick = () => {
if(this.state.count > 0) {
this.setState(this.decrement);
}
};
handleDummyOperationClick = () => {
this.setState({
timestamp: Date.now()
});
};
// Implement shouldComponentUpdate to avoid unnecessary re-renders.
shouldComponentUpdate(nextProps, nextState) {
return this.state.count !== nextState.count;
}
render() {
const { count } = this.state;
const calculatedCount = superExpensiveFunction(count);
return (
<Fragment>
<Count
onIncrement={ this.handleIncrementClick }
onDecrement={ this.handleDecrementClick }
value={ calculatedCount }
/>
<button className="Counter__button" onClick={this.handleDummyOperationClick}>Dummy</button>
</Fragment>
);
}
}
export default Counter;