安裝的方法
當一個組件的實例被創(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指向會錯誤。
constructor(props, context) {
super(props, context)
console.log(this.props, this.context) // 在內(nèi)部可以使用props和context
}
componentWillMount()
該生命周期即將被遺棄,可以持續(xù)到 React 17 版本
執(zhí)行的時機:
1、組件剛經(jīng)歷constructor,初始完數(shù)據(jù)
2、組件還未進入render,組件還未渲染完成,dom還未渲染
componentWillMount() {
}
static getDerivedStateFromProps(props, state)
React 16 版本加入的生命周期
執(zhí)行的時機:
1、組件剛經(jīng)歷constructor,初始完數(shù)據(jù)
2、在 render 方法之前
3、必須有返回值,返回一個對象更新state,或者返回null
static getDerivedStateFromProps(props, state) {
return { title: 'F2' }
}
render()
render方法是組件必須的方法。
當render方法被調(diào)用,將檢查this.props 和 this.state,并且有一個返回值。
render方法的返回值類型如下:
React elements
在render中返回一個DOM節(jié)點。
通過JSX語法創(chuàng)建,例如:<View />,也可以是自己定義的組件<MyComponent />。
render() {
return (
<View style={styles.container} />
);
}
Arrays and fragments
可以在render方法中返回多個元素
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()
在組件安裝完成后(組件實例插入到DOM樹中)立即被調(diào)用。網(wǎng)絡(luò)請求、設(shè)置監(jiān)聽等操作可以放到這個方法中。
方法的執(zhí)行順序
constructor、componentWillMount和render的執(zhí)行順序:頂層父組件 -> 子組件 -> 子組件 ->...-> 底層子組件
componentDidMount執(zhí)行順序:底層子組件 -> 子組件 -> 子組件 ->...-> 頂層父組件
更新的方法
componentWillReceiveProps(nextProps)
static getDerivedStateFromProps()
同上
shouldComponentUpdate(nextProps, nextState)
在組件收到props或state發(fā)生變化時被調(diào)用。
默認返回true,表示要刷新組件。
在此方法中可以根據(jù)需要避免不必要的刷新。
render()
同上
componentWillUpdate(nextProps,nextState)
getSnapshotBeforeUpdate(prevProps, prevState)
React 16 版本加入的生命周期
update發(fā)生的時候,在render之后,在組件dom渲染之前。
返回一個值,作為componentDidUpdate的第三個參數(shù)。
componentDidUpdate(prevProps, prevState)
在組件發(fā)生更新之后會被立即調(diào)用,但是在初始化的時候不會被調(diào)用。
當組件的props或state發(fā)生變化時,這個方法也是處理網(wǎng)絡(luò)請求等操作比較好的地方。
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
卸載的方法
componentWillUnmount()
在組件被卸載并且摧毀之前調(diào)用。