释放双眼,带上耳机,听听看~!
一、React生命周期
- getDefaultProps:初始化Props属性,Props来自于父组件或者其他组件传递过来的。
- getInitialState:初始化我们当前组件的状态。
- componentWillMount:组件在初始化之前会调用这个方法。
- render:渲染UI。
- componentDidMount:组件渲染完成之后会调用这个方法。
- componentWillReceiveProps:父组件的传递东西过来时会调用这个方法。
- shouldComponentUpdate:组件更新时调用。
- componnetWillUpdate:组件更新前调用。
- componentDidUppdate:组件更新后调用。
- componentWillUnmount:组件销毁时调用
1.父组件Life.js
父组件为Life.js,里面有两个按钮,作用为把当前组件的count属性+1
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 1import React from 'react';
2import ChildLife from './ChildLife';
3
4/**
5 * 父组件
6 */
7class Life extends React.Component {
8
9 //构造器
10 constructor(props){
11 super(props);
12
13 this.state = { //组件内的变量等都通过state来存取
14 count : 0
15 };
16 }
17
18 /**
19 * 点击事件的第一种实现方式:
20 */
21 addCount = ()=>{
22 this.setState({
23 count : this.state.count + 1
24 })
25 }
26
27 /**
28 * 点击事件的第二种实现方式:
29 */
30 addCountBindThis(){
31 this.setState({
32 count : this.state.count + 1
33 })
34 }
35
36 render() {
37 return (
38 <div>
39 <p>看一下React生命周期</p>
40 <button onClick={this.addCount}>按钮1:不使用bind</button>
41 <button onClick={this.addCountBindThis.bind(this)}>按钮2:使用bind</button>
42 <p>{this.state.count}</p>
43 <ChildLife parentCount = {this.state.count}></ChildLife>
44 </div>
45 )
46
47 }
48}
49export default Life;
50
51
2.子组件ChildLife.js
父组件传递父组件的count给子组件,名称为parentCount,子组件进行展示。
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 1import React from 'react';
2
3/**
4 * 子组件
5 */
6class ChildLife extends React.Component{
7
8 constructor(props){
9 super(props);
10 this.state={
11 count : 0
12 };
13 }
14
15 /** 生命周期们 **/
16
17 componentWillMount() { //组件在初始化之前会调用这个方法
18 console.log("componentWillMount() -> 组件在初始化之前会调用这个方法");
19 }
20
21 componentDidMount() { //组件渲染完成之后会调用这个方法
22 console.log("componentDidMount() -> 组件渲染完成之后会调用这个方法");
23 }
24
25 componentWillReceiveProps(newProps) { //父组件的传递东西过来时会调用这个方法
26 console.log("componentWillReceiveProps() -> 父组件的传递东西过来时会调用这个方法");
27 console.log(newProps.parentCount)
28 }
29
30
31
32 render() {
33 return(
34 <div>
35 <p>子组件:</p>
36 <p>{this.props.parentCount}</p>
37 </div>
38 )
39 }
40
41}
42
43export default ChildLife;
44
45
46
3.配置下路由让我们能够测试
项目是基于ant design pro2,修改config/router.config.js