1.旧版生命周期
-
初始化阶段:由ReactDOM.render()触发 -----初次渲染
- constructor()
- componentWillMount()
- render()
- componentDidMount() ===== 常用
一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息
-
更新阶段:由组件内部 this.setState() 或父组件render触发
- shoudComponentUpdate()
- componentWillUpdate()
- render() ==- 必须使用
- componentDidUpdate()
-
卸载组件:由ReactDOM.unmountComponentAtNode()触发
- componentWillUnmount() === 常用
一般在这个钩子中做一些收尾的事,如:关闭定时器、取消订阅消息
- componentWillUnmount() === 常用
2. 新版生命周期
- 初始化阶段:由ReactDOM.render()触发--------初次渲染
- constructor()
getDerivedStateFromProps()
- render()
- componentDidMount() ====== 常用
一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求,订阅信息
- 更新阶段:由组件内部 this.setState() 或父组件重新 render触发
getDerivedStateFromProps
- shouldComponentUpdate()
getSnapshotBeforeUpdate() :创建update前的快照,返回的结果在 componentDidUpdate 可接收
- componentDidUpdate()
- 卸载组件:由ReactDOM.unmountComponentAtNode()触发
- componentWillUnmount() ==== 常用
一般 在这个钩子中做一些收尾的事,例如:关闭定时器、取消订阅信息
- componentWillUnmount() ==== 常用
案例:滚动框内容不断增加,滚动条固定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>
<style>
.listCon {
width: 300px;
height: 180px;
background-color: skyblue;
overflow: auto;
}
.list {
height: 30px;
list-style: none;
}
</style>
</head>
<body>
<div id="app"></div>
</body>
<script type="text/babel">
class List extends React.Component {
state = {
newsList: []
};
componentDidMount() {
setInterval(() => {
let {
newsList} = this.state;
this.setState({
newsList: ['当前索引:' + newsList.length, ...newsList]})
}, 1000)
}
// 获取 update之前快照,传递给 componentDidUpdate
getSnapshotBeforeUpdate() {
return this.refs.list.scrollHeight;
}
componentDidUpdate(preProps, preState, height) {
console.log({
height});
this.refs.list.scrollTop += this.refs.list.scrollHeight - height;
}
render (){
return (
<div className="listCon" ref="list">
{
this.state.newsList.map((list, index) => {
return <div className="list" key={
index}>{
list}</div>
})
}
</div>
)
}
}
ReactDOM.render(<List />, document.getElementById('app'))
</script>
</html>
效果: