React 的生命周期:官方API
下面這個方法是組件第一次加載時執(zhí)行
- constructor() :最先調(diào)用用
- componentWillMount() :render 前立即執(zhí)行
- render() : 插入到DOM
- componentDidMount() : render()后立馬運行,且只會運行一次
state 或props更新時,會觸發(fā)render()重新執(zhí)行,而以下這些方法在render()再次執(zhí)行前執(zhí)行:
- componentWillReceiveProps(nextProps) : 在接收到新的props時,this.props并未被更新,nextProps 就是新的props
- shouldComponentUpdate() :默認(rèn)是每次state改變時,都會重新render(). 但是它在第一次render不會運行,在forceUpdate()時不會運行。return false時,render()不會執(zhí)行
- componentWillUpdate() : 組件更新(render()確定要執(zhí)行了)前的一步,這兒不能更改state。 你能想到:shouldComponentUpdate() returnfalse時,它不會運行
- render() : 更新DOM
- componentDidUpdate(),gengxinDOM后立即執(zhí)行
組件完結(jié),開始銷毀:
- componentWillUnmount() : 組件被銷毀前,一般用來去掉事件監(jiān)聽,或者一些全局綁定,就是那些JS垃圾回收機(jī)制不會自動回收的東西
React的其他API:
- setState() : 修改state
- forceUpdate():這個不會導(dǎo)致shouldComponentUpdate() 運行,但是子組件的shouldComponentUpdate() 會執(zhí)行,這個東西要少用。
- defaultProps : 給props設(shè)置默認(rèn)值。
- propTypes:給props內(nèi)的參數(shù)設(shè)置類型限制,或者必填規(guī)則(就是一定要有這個參數(shù))