Props 外部數(shù)據(jù)
Props的作用
- 1.接受外部數(shù)據(jù)(只能讀不能寫低缩,外部數(shù)據(jù)由父組件傳遞
- 2.接受外部函數(shù)(在恰當(dāng)時(shí)機(jī)調(diào)用該函數(shù) 該函數(shù)一般是父組件的函數(shù)
如何讀取Props外部數(shù)據(jù)
this.props是外部數(shù)據(jù)對(duì)象的地址
super的作用就是把props放進(jìn)this里面
state 和 setState
this.setState({newState:fn})
//注意setstate不會(huì)立刻改變this.state 會(huì)在當(dāng)前代碼運(yùn)行完之后再去更新this.state從而觸發(fā)UI更新
this.setState((state,props)=>({fn}))
//這種方式會(huì)立刻執(zhí)行fn操作然后再更新UI
生命周期
函數(shù)列表
constructor() 在這里作用是初始化state
shouldComponentUpdate() 如果return false則會(huì)阻止更新
componentDidMount() 組件掛載后執(zhí)行的函數(shù)
conmponentDidUpdate() 組件更新后執(zhí)行的函數(shù)
componentWillUnmount() 組件將死
constructor
shouldComponentUpadate
example(實(shí)現(xiàn)onclick后對(duì)比前后兩次的n是否變化 如沒(méi)有變化就不要render)(但好像直接用PureComponent就可以自動(dòng)對(duì)比)
import React from 'react';
class App extends React.Component{
constructor(props){
super(props)
this.state = {
n: 1
}
}
onClick = ()=>{
this.setState(state =>({n: state.n +1}))//是setState接收一個(gè)回調(diào),這個(gè)回調(diào)可以通過(guò)參數(shù)獲取到state
this.setState(state =>({n: state.n -1}))
};
shouldComponentUpdate(newProps, newState){//這里的聲明必須要寫全 意思是如果onclick后前后兩次的n值不變 就不用render了
if(newState.n === this.state.n){
return false
}else{
return true
}
}
render(){
console.log('render過(guò)了一次')
return(
<div>App
<div>{this.state.n} <button onClick = {this.onClick}>+1</button>
</div>
</div>
)
}
}
export default App
面試題:shouldComponentUpdate有什么用
它允許我們手段判斷是否需要進(jìn)行組件更新削葱,我們可以根據(jù)應(yīng)用場(chǎng)景靈活的設(shè)置返回值 以避免不必要的更新
render(展示視圖 創(chuàng)建虛擬DO M)
componentDidMount(掛載后執(zhí)行的函數(shù))
componentDidUpdate(prevProps, prevState, snapshot?)(更新數(shù)據(jù)后執(zhí)行的代碼)
componentWillUnmount(誰(shuí)污染誰(shuí)治理)
summary
構(gòu)造=>渲染=>掛載