react浅析

Change is the only proof of life. —— Evelyn Waugh 《Brideshead Revisited》

所有在JSX中声明的函数,都会被委托在最顶层的document节点上,并用组件名和事件名来存储回调函数,
每次当某个组件触发事件时,在document上绑定的监听函数就会找到这个组件和他所有的父组件,
对每个组件创建对应的react合成事件,并批处理,从而根据事件名和组件名调用回调函数

关于setState

  • 原理:在执行this.setState()时,react并没有急着立即更新state,而是把新的state存到一个队列中。对传进去的对象进行合并,然后在统一处理,触发重新渲染过程。
  • setState()并不会立即改变this.state,而是创建一个即将处理的state。setState()并不一定是同步的。为了提升性能React会批量执行state()和DOM渲染
  • setState()总是会触发一次组件重绘,除非在showComponentUpdate()中实现了一些条件条件渲染逻辑
  • 把setState()看做是重新render的一次请求而不是立即更新组件的指令

Q:调用this.setState()后什么时候this.state才会更新?
A:即将要执行下一次的render函数时

组件的生命周期

为了更清楚明了的查看组件的生命周期,在每一个生命周期中添加改生命周期的名称
发现
初次调用时

  • father was created
  • father componentWillMount
  • render father
  • child was created
  • child compoentWillMount
  • render Child
  • Child componentDidMount
  • Father componentWillUnmount

调用父组件的setState后

  • Father shouldCompoentUpdate
  • Father compoentWillpdate
  • Father render
  • Child componentWillReceiveProps
  • Child shouldComponentUpdate
  • Child componentWillUpdate
  • render Child
  • Child ComponentDidUpdate
  • Father CompoentDidUpdate
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
class Child extends React.Component {
constructor() {
super()
console.log('Child was created!')
}
componentWillMount(){
console.log('Child componentWillMount!')
}
componentDidMount(){
console.log('Child componentDidMount!')
}
componentWillReceiveProps(nextProps){
console.log('Child componentWillReceiveProps:'+nextProps.data )
}
shouldComponentUpdate(nextProps, nextState){
console.log('Child shouldComponentUpdate:'+ nextProps.data)
return true
}
componentWillUpdate(nextProps, nextState){
console.log('Child componentWillUpdate:'+ nextProps.data)
}
componentDidUpdate(){
console.log('Child componentDidUpdate')
}
render() {
console.log('render Child!')
return (
<h1>Child recieve props: {this.props.data}</h1>
);
}
}

class Father extends React.Component {
// ... 前面跟子组件一样
handleChangeState(){
this.setState({randomData: Math.floor(Math.random()*50)})
}
render() {
console.log('render Father!')
return (
<div>
<Child data={this.state.randomData} />
<h1>Father State: { this.state.randomData}</h1>
<button onClick={this.handleChangeState}>切换状态</button>
</div>
);
}
}

React.render(
<Father />,
document.getElementById('root')
);

react时间周期

组件生命周期 参考