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