组件加载
当组件被实例化并且插入Dom时所执行的方法,也会按照下的顺序依次执行。
constructor()
构造方法。
这个方法有两个目的:
初始化一个本地state。
this.state = {color: ‘red’};
要避免将props参数直接赋值给state, this.state = {color: props.color}是不允许 的
绑定方法。
我们知道React Class中是不会继承this的,如果在class的方法中使用this,那么我们需要将this绑定到方法中。
this.clickHandler = this.clickHandler.bind(this);
绑定this,将需要super(props),否则会提示找不到this.
示例:
constructor(props) {
super(props);
this.state = {color: ‘red’};
this.clickHandler = this.clickHandler.bind(this);
}
static getDerivedStateFromProps()
当本地state需要根据props来改变的时候可调用此方法。
这个方法是在render()前会被执行,只要执行render()都会被在之前被触发。
该方法有两个参数props和state; 返回值为state对象, 不需要返回整体state,把需要改变的state返回即可。
示例:
static getDerivedStateFromProps(props, state) {
if(props.color !== state.color) {
return {color: props.color};
}
}
render()
这个方法是React组件中必须要提供的方法。当state或者props任一数据有更新时都会执行。
需要注意当继承PureComponent时,不会对对象进行深度比较,也就是,不会根据对象内的对象变化时执行render().
render()是一个纯函数,也就是不能在这个方法中有类似setState()这样的行为。
返回的数据类型可以有:
null、String、Number、Array、Boolean。
React elements
Fragment
Portal
注意:不能返回undefined.
当shouldComponentUpdate()返回false时,无论state和props有没有变化,这个方法都不执行。
示例:
render() {
return (
<div>{this.state.color}</div>
);
}
componentDidMount()
componentDidMount()方法是在组件加载完后立即执行,也就是当该组件相关的dom节点插入到dom树中时。该方法在组件生命中只执行一次。
一般情况,我们会在这里setState()根据props的值,也可以从这里调用接口,获取服务端的数据,也可以在这里监听websocket、setInterval等操作。
注意:一些监听需要在组件卸载时清理掉,否则会引起异常。
示例:
componentDidMount() {
this.setState({color: this.props.color});
}
在线示例
推荐阅读《React 手稿》
发表回复