1.旧版生命周期
React的生命周期大致可以分为三个阶段:挂载阶段、渲染(更新)阶段、卸载阶段,如下图:
-
初始化阶段:由ReactDOM.render()触发 -----初次渲染
-
constructor(props) 接收props和context,当想在函数内使用这两个参数需要在super传入参数,当使用 constructor时必须使用super,否则可能会有this的指向问题;如果不初始化state或者不进行方法绑定,则可以不在组件写构造函数。
-
componentWillMount() 挂载之前(也就是render之前)被调用。 在服务端渲染唯一会调用的函数,代表已经初始化数据但是没有渲染dom,因此在此方法中同步调用 setState() 不会触发额外渲染。
-
render() render函数会插入jsx生成的dom结构,react会生成一份虚拟DOM树,在每一次组件更新时,在此react会通过其diff算法比较更新前后的新旧DOM树,比较以后,找到最小的有差异的DOM节点,并重新渲染
-
componentDidMount() ===== 常用 在组件挂载后(插入到DOM树后)立即调用 一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息
-
-
更新阶段:由组件内部 this.setState() 或父组件render触发
-
shoudComponentUpdate() 在渲染之前被调用,默认返回true,在state发生变化时,都会去调用该钩子。
-
componentWillUpdate() 当组件接收到新的props和state会在渲染前调用,初始渲染不会调用该方法。
-
render() ==- 必须使用
-
componentDidUpdate()
-
-
卸载组件:由ReactDOM.unmountComponentAtNode()触发
- componentWillUnmount() === 常用 一般在这个钩子中做一些收尾的事,如:关闭定时器、取消订阅消息
2. 新版生命周期
- 初始化阶段:由ReactDOM.render()触发--------初次渲染
- constructor()
getDerivedStateFromProps()- render()
- componentDidMount() ====== 常用 一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求,订阅信息
- 更新阶段:由组件内部 this.setState() 或父组件重新 render触发
getDerivedStateFromProps- shouldComponentUpdate()
getSnapshotBeforeUpdate() :创建update前的快照,返回的结果在 componentDidUpdate 可接收- componentDidUpdate()
- 卸载组件:由ReactDOM.unmountComponentAtNode()触发
- 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>
效果如下所示: