重要的鉤子
1.render:初始化渲染或更新渲染調(diào)用
2.componentDidMount:開啟監(jiān)聽节榜,發(fā)送ajax請(qǐng)求
3.componentWillUnmount:收尾工作
生命周期(新)
1.初始化階段:由ReactDOM.render()觸發(fā)—初次渲染
(1). constructor
(2). getDerivedStateFromProps //從Props得到一個(gè)派生的狀態(tài)肥照,即state的值任何時(shí)候都取決與props淹仑,派生狀態(tài)會(huì)導(dǎo)致代碼冗余組件難以維護(hù)挺狰,罕見
(3). render()
(4). componentDidMount() ===>常用:開啟定時(shí)器只损,發(fā)送網(wǎng)絡(luò)請(qǐng)求壮不,訂閱消息
2.更新階段:由組件內(nèi)部this.setState()或父組件重新render觸發(fā)
(1). getDerivedStateFromProps
(2). shouldComponentUpdate()
(3). render()
(4. getSnapshotBeforeUpdate //得到快照
(5). componentDidUpdate()
3.卸載組件:由ReactDOM.unmountComponentAtNode()觸發(fā)
(1). componentWillUnmount() ===>常用:關(guān)閉定時(shí)器蔼夜,取消訂閱消息
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'))
}
//強(qiáng)制更新不改狀態(tài)
force = ()=>{
this.forceUpdate()
}
//從Props得到一個(gè)派生的狀態(tài)判呕,即state的值任何時(shí)候都取決與props尘喝,派生狀態(tài)會(huì)導(dǎo)致代碼冗余組件難以維護(hù)磁浇,罕見
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>當(dāng)前求和為</h2>
<button onClick="this.add">點(diǎn)我+1</button>
<button onClick="this.death">卸載組件</button>
<button onClick="this.force">不更改任何狀態(tài)中的數(shù)據(jù),強(qiáng)制更新一下</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'))