constructor()
初始化 props,当只有以下四行时可省略
constructor(props){
super(props);
}
初始化 state
constructor(){
super();
this.state = {n:0}
}
用来 bind this
constructor() {
this.onClick = this.onClick.bind(this);
}
// 新语法
onClick = () => {}
render()
创建虚拟 DOM()
只能有一个根元素,若有两个根元素则用
使用JSX语法:可用 if..else,问好表达式,for循环需要用数组或使用 array.map
shouldComponentUpdate()
返回 true 表示更新,返回 false 阻止更新
作用:允许我们手动判断是否要进行组件更新,可根据引用场景灵活地设置返回值,以避免不必要地更新
componentDidMount()
元素插入页面后执行,首次渲染执行
官方推荐此处发起加载数据地 AJAX 请求
可在此处获取元素高度
componentDidUpdate()
视图更新后执行,首次渲染不执行
此处可发起 AJAX 请求用于更新文档
此处使用 setState 可能引起无限循环,应该放在 if 里
若 shouldComponentUpdate() 返回 false 则不促发次钩子
componentWillUnmount()
组件将要被移除页面然后被销毁时执行
unmount 过的组件不会再次 mount
从性能上考虑,在 componentDidMount 里的长久持续性操作要在这里销毁:
- 在 mount 里监听了 window scroll,在 unmount 取消
- 在 mount 里创建了 Timer(计时器),在 unmount 取消
- 在 mount 里创建了 AJAX 请求,在 unmount 取消