react要点

react的生命周期

react的周期可以通过一张图很直观的表示出来,如下图所示:

react生命周期

下面通过一个实例,更直观的展示这一过程:

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
class LifeCycle extends React.Component {
constructor(props) {
super(props);
alert("Initial render");
alert("constructor");
this.state = {str: "hello"};
}
componentWillMount() {
alert("componentWillMount");
}
componentDidMount() {
alert("componentDidMount");
}
componentWillReceiveProps(nextProps) {
alert("componentWillReceiveProps");
}
shouldComponentUpdate() {
alert("shouldComponentUpdate");
return true; // 记得要返回true
}
componentWillUpdate() {
alert("componentWillUpdate");
}
componentDidUpdate() {
alert("componentDidUpdate");
}
componentWillUnmount() {
alert("componentWillUnmount");
}
setTheState() {
let s = "hello";
if (this.state.str === s) {
s = "HELLO";
}
this.setState({
str: s
});
}
forceItUpdate() {
this.forceUpdate();
}
render() {
alert("render");
return(
<div>
<span>{"Props:"}<h2>{parseInt(this.props.num)}</h2></span>
<br />
<span>{"State:"}<h2>{this.state.str}</h2></span>
</div>
);
}
}
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {
num: Math.random() * 100
};
}
propsChange() {
this.setState({
num: Math.random() * 100
});
}
setLifeCycleState() {
this.refs.rLifeCycle.setTheState();
}
forceLifeCycleUpdate() {
this.refs.rLifeCycle.forceItUpdate();
}
unmountLifeCycle() {
// 这里卸载父组件也会导致卸载子组件
React.unmountComponentAtNode(document.getElementById("container"));
}
parentForceUpdate() {
this.forceUpdate();
}
render() {
return (
<div>
<a className="btn_primary" onClick={this.propsChange.bind(this)}>propsChange</a>
<a className="btn_primary" onClick={this.setLifeCycleState.bind(this)}>setState</a>
<a className="btn_primary" onClick={this.forceLifeCycleUpdate.bind(this)}>forceUpdate</a>
<a className="btn_primary" onClick={this.unmountLifeCycle.bind(this)}>unmount</a>
<a className="btn_primary" onClick={this.parentForceUpdate.bind(this)}>parentForceUpdateWithoutChange</a>
<LifeCycle ref="rLifeCycle" num={this.state.num}></LifeCycle>
</div>
);
}
}
ReactDom.render(
<Container></Container>,
document.getElementById('container')
);

使用react实现应用

先创建静态版本,再创建动态版本。

静态版本:用props来传递数据;动态版本:用state传递数据。

较简单例子:自顶向下构建项目,较大的项目:自底向上构建项目更利于编写测试。

react高级语法

默认为true

下面两种语法等价:

1
2
3
<MyTextBox autocomplete /> // 默认为true
<MyTextBox autocomplete={true} />

{foo}{foo: foo} 的简写,而不是 {foo: true}

扩展属性(谨慎使用)

1
2
3
4
5
6
7
8
function App1() {
return <Greeting firstName="Ben" lastName="Hector" />;
}
function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...props} />; // 用...传递整个属性对象
}