1class Example extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {
5 count: 0
6 };
7 }
8
9 render() {
10 return (
11 <div>
12 <p>You clicked {this.state.count} times</p>
13 <button onClick={() => this.setState({ count: this.state.count + 1 })}>
14 Click me
15 </button>
16 </div>
17 );
18 }
19}
1// Correct
2this.setState(function(state, props) {
3 return {
4 counter: state.counter + props.increment
5 };
6});
1handleChange: function (e) {
2 // 1. Make a shallow copy of the items
3 let items = [...this.state.items];
4 // 2. Make a shallow copy of the item you want to mutate
5 let item = {...items[1]};
6 // 3. Replace the property you're intested in
7 item.name = 'newName';
8 // 4. Put it back into our array. N.B. we *are* mutating the array here, but that's why we made a copy first
9 items[1] = item;
10 // 5. Set the state to our new copy
11 this.setState({items});
12},
13
1You have to use setState() for updating state in React
2{
3 hasBeenClicked: false,
4 currentTheme: 'blue',
5}
6
7setState({
8 hasBeenClicked: true
9});
10
1You have to use setState() for updating state in React
2{
3 hasBeenClicked: false,
4 currentTheme: 'blue',
5}
6
7setState({
8 hasBeenClicked: true
9});
1class Car extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {
5 brand: "Ford",
6 model: "Mustang",
7 color: "red",
8 year: 1964
9 };
10 }
11 changeColor = () => {
12 this.setState({color: "blue"});
13 }
14 render() {
15 return (
16 <div>
17 <h1>My {this.state.brand}</h1>
18 <p>
19 It is a {this.state.color}
20 {this.state.model}
21 from {this.state.year}.
22 </p>
23 <button
24 type="button"
25 onClick={this.changeColor}
26 >Change color</button>
27 </div>
28 );
29 }
30}