react context 用法
const HahaContext = React.createContext();
class Parent extends React.Component{
render(){
return (
<HahaContext.Provider value={this.state}>
<Child></Child>
<HahaContext.Provider />
)
}
}
class Child extends React.Component{
static contextType = HahaContext;
render(){
return (<div>{this.context}</div>)
}
}
如果子組件為函數(shù)式組件使用
function Child(props){
return (
<HahaContext.consumer>
{value => (<h3>value</h3>)}
</HahaContext.consumer>
)
}
react 生命周期
老版
掛載,更新铃芦,卸載
掛載:
1.constructor
初始化props
初始化state
2. willmount [簡寫]
3. render 將虛擬dom掛載到真實dom上
4. didmount [簡寫]
組件第一次渲染完成雅镊,此時dom節(jié)點已經(jīng)生成
更新:
1.WillReceiveProps[簡寫]
props變化
子組件state承接props,當props變化用于更新state
2.shouldupdate[簡寫]
state變化
性能優(yōu)化
解決父組件重傳
因為react父組件的重新渲染會導致其所有子組件的重新渲染杨帽,這個時候其實我們是不需要所有子組件都跟著重新渲染的漓穿,因此需要在子組件的該生命周期中做判斷
3.willupadate
4.render
render函數(shù)會插入jsx生成的dom結構,react會生成一份虛擬dom樹注盈,在每一次組件更新時晃危,在此react會通過其diff算法比較更新前后的新舊DOM樹,比較以后,找到最小的有差異的DOM節(jié)點僚饭,并重新渲染震叮。
5.didupdate
新版
getDerivedStateFromProps
getDerivedStateFromProps +didUpdate 代替 WillReceiveProps
SnapshotBeforeUpdate
SnapshotBeforeUpdate+ didUpdate 代替 willupdate