生命周期
正常情况下,你应该使用组件类的方式来创建React组件
为此React.Component提供了一系列的生命周期(Hook)来辅助完善一个组件的渲染过程,也许你用的上,不是么。这一篇文章也许有那么一些“官方”,虽然这很不好,但我想这些方法还需要你理解和牢记,这样才能运用得当。
初始化props和state
在ES2015中初始化状态下的props需要做为类的静态属性,而state则是实例属性。
class Hello extends React.Component{
constructor (props){
super(props);
this.state = {
show: false
};
this.buttonHandler = this.buttonShow.bind(this);
this.delay = true;
}
}
Hello.defaultProps = {};
理解生命周期
且定义一个普通的组件:
import React from 'react';
import { render, findDOMNode } from 'react-dom';
class Hello extends React.Component {
componentWillMount (){
}
render (){
const { children } = this.props;
return (
<div>
{ children }
</div>
);
}
componentDidMount (){
}
}
render((
<Hello>
<span>H</span>
<span>W</span>
</Hello>
),document.getElementById('app'));
这并未有太多的理论知识,可以遇见的是我们首先要学习的是componentWillMount
和componentDidMount
方法,前者在render被调用之前得到执行,后者在render被调用之后得到执行,这一个过程在理论上,我们可以得到什么好处呢?
在我们实现的ActionSheet
中,如果想在Web应用被用户第一次访问时就弹起ActionSheet
效果,让其二选一。
这个时候,就需要在componentWillMount
方法中重新设置一下state中的show属性为true。
componentWillMount (){
this.setState({
show: true
})
}
那么componentDidMount
方法又有何意义呢?一般来说如果我们想获取真实的DOM节点,你就需要在这里来获取。
componentDidMount (){
this.containerDiv = findDOMNode(this);
}
接下来,我们再看看其他需要某些条件达到而获取的执行的方法:
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- componentDidUpdate
- componentWillUnmount
componentWillUnmount
我想应该会比较好理解,当你使用Router系统时,页面切换,根组件将在卸载之前调用,理论上在这个里面,可以将一些用到的对象,解除引用关系,设置为null。
那么问题来了,componentDidUpdate
和componentWillUpdate
究竟有什么用?
componentWillUpdate (nextProps,nextState){
console.log(nextState)
}
componentDidUpdate (preProps,preState){
console.log(preState)
}
componentDidUpdate
当你的组件重新更新到DOM之后被调用,在这里可以将之前在componentDidMount
中获取的DOM对象引用更新一下。componentWillUpdate
是你调用setState
方法设置新的state时,并且接收到之前获得执行,在这个方法中,可以存在这么一个场景,比如我们在更新某个UI时,在此之前我们对其他的一些事情做一些准备工作。
重点理解:shouldComponentUpdate和componentWillReceiveProps
componentWillReceiveProps
可以提供在render
调用之前更改state的机会,而且新的props通过参数传递给你,老的可以通过this.props
获取到。这个东西在某些情况下非常的有用。
componentWillReceiveProps(nextProps){
console.log(nextProps);
console.log(this.props);
}
而shouldComponentUpdate
可以在优化性能方面有着显著的作用,它传递了一对新旧的值过来。
shouldComponentUpdate (nextProps, nextState) {
return nextProps.id !== this.props.id;
}
通过返回的bool
值来控制render方法究竟需不需执行,当你有成千上百个子组件的时候,我们可以通过它来优化你的Web应用。