安裝的方法
當(dāng)一個(gè)組件的實(shí)例被創(chuàng)建并被插入到DOM結(jié)構(gòu)中,按下 constructor -> componentWillMount / getDerivedStateFromProps -> render -> componentDidMount
的順序調(diào)用方法。
constructor(props, context)
關(guān)于ES6的class constructor和super郑叠,只要組件存在constructor, 就必要要寫super, 否則this指向會(huì)錯(cuò)誤率拒。
constructor(props, context) {
super(props, context)
console.log(this.props, this.context) // 在內(nèi)部可以使用props和context
}
componentWillMount()
該生命周期即將被遺棄叶撒,可以持續(xù)到 React 17 版本
執(zhí)行的時(shí)機(jī):
1垫毙、組件剛經(jīng)歷constructor河咽,初始完數(shù)據(jù)
2蛆橡、組件還未進(jìn)入render舌界,組件還未渲染完成,dom還未渲染
componentWillMount() {
}
static getDerivedStateFromProps(props, state)
React 16 版本加入的生命周期
執(zhí)行的時(shí)機(jī):
1泰演、組件剛經(jīng)歷constructor呻拌,初始完數(shù)據(jù)
2、在 render 方法之前
3睦焕、必須有返回值藐握,返回一個(gè)對(duì)象更新state,或者返回null
static getDerivedStateFromProps(props, state) {
return { title: 'F2' }
}
render()
render方法是組件必須的方法垃喊。
當(dāng)render方法被調(diào)用猾普,將檢查this.props 和 this.state,并且有一個(gè)返回值本谜。
render方法的返回值類型如下:
React elements
在render中返回一個(gè)DOM節(jié)點(diǎn)抬闷。
通過(guò)JSX
語(yǔ)法創(chuàng)建,例如:<View />
耕突,也可以是自己定義的組件<MyComponent />
笤成。
render() {
return (
<View style={styles.container} />
);
}
Arrays and fragments
可以在render方法中返回多個(gè)元素
render () {
return (
[
<View style={{ flex: 1, backgroundColor: 'red' }} />,
<View style={{ flex: 1, backgroundColor: 'blue' }} />
]
)
}
render () {
return (
<React.Fragment>
<View style={{ flex: 1, backgroundColor: 'red' }} />
<View style={{ flex: 1, backgroundColor: 'blue' }} />
</React.Fragment>
)
}
Portals
String and numbers
Booleans or null
render () {
return (
true && <View style={{ flex: 1, backgroundColor: 'red' }} />
)
}
render () {
return (
false && <View style={{ flex: 1, backgroundColor: 'red' }} />
)
}
componentDidMount()
在組件安裝完成后(組件實(shí)例插入到DOM樹(shù)中)立即被調(diào)用。網(wǎng)絡(luò)請(qǐng)求眷茁、設(shè)置監(jiān)聽(tīng)等操作可以放到這個(gè)方法中炕泳。
方法的執(zhí)行順序
constructor
、componentWillMount
和render
的執(zhí)行順序:頂層父組件 -> 子組件 -> 子組件 ->...-> 底層子組件
componentDidMount
執(zhí)行順序:底層子組件 -> 子組件 -> 子組件 ->...-> 頂層父組件
更新的方法
componentWillReceiveProps(nextProps)
static getDerivedStateFromProps()
同上
shouldComponentUpdate(nextProps, nextState)
在組件收到props或state發(fā)生變化時(shí)被調(diào)用上祈。
默認(rèn)返回true培遵,表示要刷新組件。
在此方法中可以根據(jù)需要避免不必要的刷新登刺。
render()
同上
componentWillUpdate(nextProps,nextState)
getSnapshotBeforeUpdate(prevProps, prevState)
React 16 版本加入的生命周期
update發(fā)生的時(shí)候籽腕,在render之后,在組件dom渲染之前纸俭。
返回一個(gè)值皇耗,作為componentDidUpdate的第三個(gè)參數(shù)。
componentDidUpdate(prevProps, prevState)
在組件發(fā)生更新之后會(huì)被立即調(diào)用揍很,但是在初始化的時(shí)候不會(huì)被調(diào)用郎楼。
當(dāng)組件的props或state發(fā)生變化時(shí)万伤,這個(gè)方法也是處理網(wǎng)絡(luò)請(qǐng)求等操作比較好的地方。
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
卸載的方法
componentWillUnmount()
在組件被卸載并且摧毀之前調(diào)用呜袁。