每一個React組件在加載時都有特定的生命週期,在此期間不同的方法會被執行。
組件加載: componentWillMount
componentWillMount()
componentWillMount
會在組件render
之前執行,並且永遠都只執行一次。
由於這個方法始終只執行一次,所以如果在這裏定義了setState
方法之後,頁面永遠都只會在加載前更新一次。
組件加載: componentDidMount
componentDidMount()
這個方法會在組件加載完畢之後立即執行。在這個時候之後組件已經生成了對應的DOM結構,可以通過this.getDOMNode()
來進行訪問。
如果你想和其他JavaScript框架一起使用,可以在這個方法中執行setTimeout
, setInterval
或者發送AJAX請求等操作(防止異部操作阻塞UI)。
componentDidMount: function() {
setTimeout(function() {
this.setState({items: {name: 'test'}})
}, 1000)
}
組件更新: componentWillReceiveProps
componentWillReceiveProps(object nextProps)
在組件接收到一個新的prop時被執行。這個方法在初始化render時不會被調用。
Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). (不太懂這句話。。。)
舊的props可以通過this.props
來獲取。在這個函數內調用this.setState()
方法不會增加一次新的render.
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
組件更新: shouldComponentUpdate
boolean shouldComponentUpdate(object nextProps, object nextState)
返回一個布爾值。在組件接收到新的props或者state時被執行。在初始化時或者使用forceUpdate
時不被執行。
可以在你確認不需要更新組件時使用。
shouldComponentUpdate: function(nextProps, nextState) {
return nextProps.id !== this.props.id;
}
如果shouldComponentUpdate
返回false, render()
則會在下一個state
change之前被完全跳過。(另外componentWillUpdate
和 componentDidUpdate
也不會被執行)
默認情況下shouldComponentUpdate
會返回true.
By default, shouldComponentUpdate always returns true to prevent subtle bugs when state is mutated in place, but if you are careful to always treat state as immutable and to read only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.(這句也不太懂。。。)
如果你需要考慮性能,特別是在有上百個組件時,可以使用shouldComponentUpdate
來提升應用速度。
組件更新: componentWillUpdate
componentWillUpdate(object nextProps, object nextState)
在組件接收到新的props或者state但還沒有render時被執行。在初始化時不會被執行。
一般用在組件發生更新之前。
組件更新: componentDidUpdate
componentDidUpdate(object prevProps, object prevState)
在組件完成更新後立即執行。在初始化時不會被執行。一般會在組件完成更新後被使用。例如清除notification文字等操作。
Unmounting: componentWillUnmount
在組件從DOM unmount後立即執行.
componentDidMount:function(){
this.inc = setInterval(this.update,500)
},
componentWillUnmount:function(){
console.log("goodbye cruel world!")
clearInterval(this.inc)
}
主要用來執行一些必要的清理任務。例如清除setTimeout
等函數,或者任意的在componentDidMount
創建的DOM元素。
ref: http://facebook.github.io/react/docs/component-specs.html
原文地址:https://fraserxu.me/2014/08/31/react-component-lifecycle/