-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathavoid-mutation.htm
More file actions
67 lines (57 loc) · 1.49 KB
/
Copy pathavoid-mutation.htm
File metadata and controls
67 lines (57 loc) · 1.49 KB
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
59
60
61
62
63
64
65
66
67
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Avoid Mutation</title>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script type="text/jsx">
class ListOfWords extends React.PureComponent {
render() {
return <div>{this.props.words.join(',')}</div>;
}
}
class WordAdder extends React.Component {
constructor(props) {
super(props);
this.state = {
words: ['marklar']
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// This section is bad style and causes a bug
// because words is mutated and will compare equal
// inside ListOfWords since it's a PureComponent
//const words = this.state.words;
//words.push('marklar');
//this.setState({words: words});
// Not mutating the words object here
this.setState(prevState => ({
words: prevState.words.concat(['marklar'])
}));
// ES6 syntax
// this.setState(prevState => ({
// words: [...prevState.words, 'marklar'],
// }));
}
render() {
return (
<div>
<button onClick={this.handleClick}>Add</button>
<ListOfWords words={this.state.words} />
</div>
);
}
}
ReactDOM.render(
<WordAdder />,
document.getElementById('root')
);
</script>
</body>
</html>