React-setState基本應用

基本應用

2.setState使用

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
68
69
import React, {Component} from 'react';
import PropTypes from 'prop-types'

class Counter extends Component{
constructor(props){
super(props);
this.state= {
num: props.initNum,
}
}


addNum = () => {
// 來試試看num一次加2

//setState為非同步方式,所以不能期望下一個setState的num馬上+1,所以能使用下面兩招方法
this.setState({
num: this.state.num + 1,
})
this.setState({
num: this.state.num + 1,
})

//第一招 使用function 箭頭涵式
this.setState((state) => { //使用return更改值
return {
num: state.num + 1,
}
})
this.setState((state) => ({ //使用物件更改值,注意,記得{}物件外面要在包一層(),不然程式會認為是要開始寫一個涵式
num: state.num + 1,
}));

//第二招 使用callback function
this.setState((state) => ({ //執行的順序會是先跑完外面一圈的箭頭涵式,當兩個都跑完之後,再去執行callback function
num: state.num + 1,
}), () => {
setTimeout(() => { //先執行完兩個callback function,再去執行setTimeout
console.log('執行1')
}, 0);
});
this.setState((state) => ({
num: state.num + 2,
}), () => {
console.log('執行2')
});
}


render() {
return(
<div>
<h1>{this.state.num}</h1>
<button type="button" onClick={this.addNum}>+1</button>
</div>
)
}
}

Counter.defaultProps = {
initNum: 5,
}

Counter.propTypes = {
initNum: PropTypes.number,
}


export default Counter;
分享到