重要的钩子
1.render:初始化渲染或更新渲染调用
2.componentDidMount:开启监听,发送ajax请求
3.componentWillUnmount:收尾工作
生命周期(新)
1.初始化阶段:由ReactDOM.render()触发—初次渲染
(1). constructor
(2). getDerivedStateFromProps //从Props得到一个派生的状态,即state的值任何时候都取决与props,派生状态会导致代码冗余组件难以维护,罕见
(3). render()
(4). componentDidMount() ===>常用:开启定时器,发送网络请求,订阅消息
2.更新阶段:由组件内部this.setState()或父组件重新render触发
(1). getDerivedStateFromProps
(2). shouldComponentUpdate()
(3). render()
(4. getSnapshotBeforeUpdate //得到快照
(5). componentDidUpdate()
3.卸载组件:由ReactDOM.unmountComponentAtNode()触发
(1). componentWillUnmount() ===>常用:关闭定时器,取消订阅消息
class Add extends React.Component{
constructor(props){
console.log("1.constructor")
super(props)
this.state = { count:0 }
}
state = { count:0 }
add = ()=>{
const {count} = this.state
this.setState({ count:count+1 })
}
death = ()=>{
ReactDOM.unmount(document.getElementById('test'))
}
//强制更新不改状态
force = ()=>{
this.forceUpdate()
}
//从Props得到一个派生的状态,即state的值任何时候都取决与props,派生状态会导致代码冗余组件难以维护,罕见
static getDerivedStateFormProps(props,state){
console.log("getDerivedStateFormProps");
console.log(props);
console.log(state);
return props
}
//在更新之前获取快照
getSnapshotBeforeUpdate(prevProps,prevState){
console.log("getSnapshotBeforeUpdate");
return null
}
//组件挂载完毕的钩子
componentDidMount(){
console.log('4.componentDidMount');
}
//组件将要卸载的钩子
componentWillUnmount(){
console.log('conponentWillUnmount');
}
//控制组件更新的"阀门"
shouldComponentUpdate(){
console.log('shouldComponentUpdate');
return true
}
//组件更新完毕的钩子
componentDidUpdate(prevProps,prevState,snapshotValue){
console.log('componentDidUpdate',preProps,prevState,snapshotValue);
}
render(){
console.log('3.render');
const { count } = this.state
return(
<div>
<h2>当前求和为</h2>
<button onClick="this.add">点我+1</button>
<button onClick="this.death">卸载组件</button>
<button onClick="this.force">不更改任何状态中的数据,强制更新一下</button>
</div>
)
}
}
ReactDOM.render(<Count count="199" />,document.getElementById('test'))
getSnapshotBeforeUpdate
class NewsList extends Reac.Component{
state = {newsArr:[]}
componentDidMount(){
setInterval(()=>{
const {newsArr} = this.state
const news = '新闻'+(newsArr.length+1)
this.setState({news,[news,...newsArr]})
},1000)
}
getSnapshotBeforeUpdate(){
return this.refs.list.scrolHeight
}
componentDidUpdate(preProps,preState,height){
this.refs.list.scrollTop += this.refs.list.scrolHeight-height
}
render(){
return(
<div class="list" ref="list">
{
this.state.newsArr.map((n,index)=>{
return <div
key={index} class="news">新闻{n}<div>
}
}
<div>
)
}
}
ReactDOM.render(<NewList />,document.getElementById('test'))