生命周期Lifecycle
函数列表
constrctor() -在这里初始化state
static getDerivedStateFromProps()
shouldComponentUpDate() -控制组件是否需要更新
render() -创建虚拟DOM
getSnapshotBeforeUpdate()
componentDidMount() -组件已经出现在页面
componentDidUpdate() -组件已更新
componentWillUnmount() -组件将死
static getDerivedStateFromErroe()
componentDidCatch()
constructor
用途
初始化props
初始化state,但此时不能调用setState
用来写bind this
constructor(){
/* 其他代码略 */
this.onClick = this.onClick.bind(this);
}
//可以用新语法代替
onClick = () => {};
constructor(){
/* 其他代码略 */
}
shouldComponentUpDate
用途
返回true表示允许UI更新
返回false表示阻止UI更新
面试常问
问:shouldComponentUpDate有什么用?
答:它允许我们手动判断是否需要进行组件更新,我们可以根据应用场景灵活的设置返回值,以避免不必要的更新。
示例代码
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
x: 0
};
}
onClick = () => {
this.setState(state => ({x: state.x + 1}));
this.setState(state => ({x: state.x - 1}));
};
shouldComponentUpdate(nextProps, nextState, nextContext) {
if (nextState.x === this.state.x) {
return false;
} else {
return true;
}
}
render() {
console.log('更新了');
return (<div>n:{this.state.x}
<button onClick={this.onClick}>+1</button>
</div>);
}
}
React.PureComponent
如果我们需要将newState和this.state的每个属性都对比一下,如果全部相等就不更新,如果有一个不等就更新,我们就可以使用React的内置功能React.PureComponent来代替React.Component
render
用途
展示视图
return (<div>...</div>)
只能有一个根元素
如果有两个根元素,就要用<React.Fragment></React.Fragment>包起,可以缩写成<></>
技巧
render里面可以写if...else
render里面可以写?:表达式
render里面不能直接写for循环,需要使用数组
render里面可以写array.map(循环)
componentDidMount
用途
在元素插入页面后执行代码,这些代码依赖DOM
比如获取div的宽度
class App extends React.PureComponent {
const
ructor(props) {
super(props);
this.state = {
width: undefined
};
}
componentDidMount() {
const div = document.getElementById('Hello');
this.setState({width: div.getBoundingClientRect().width});
}
render() {
return (
<div id="Hello">Hello,{this.state.width}px</div>
);
}
}
此处可以发起加载数据的AJAX的请求(官方推荐)
首次渲染会执行此钩子
componentDidUpDate
用途
在视图更新后执行代码
此处也可以发起AJAX请求,用于更新数据
首次渲染不会执行此钩子
在此处setState可能会引起无限循环,除非放在if...else里面
若shouldComponentUpdate返回false,则不会触发此钩子
componentWillUnmount
用途
组件将要被移除页面然后被销毁时执行代码
unmount过的组件不会再次mount
举例
如果在componentDidMount里面创建了AJAX请求
那么就要在componentWillUnmount里面取消请求
原则就是:谁污染谁治理