什麼是生命週期函數:在某一時刻組件會自動調用執行的函數。react
import React,{ Component,Fragment } from 'react' class Note extends Component{ //在組件建立的那一刻就會執行,不過是es6語法的,不能算生命週期函數 //Initialization初始化時在這裏定義state,接收props constructor(props){ super(props); //當組件的state,props發生改變的時候render會從新執行 this.state={ inputValue:'', list:[112] } } //組件第一次即將被掛載到頁面的時候,自動執行 componentWillMount(){ console.log('componentWillMount'); } //組件組件第一次掛載到頁面以後,自動被執行 componentDidMount(){ console.log('componentDidMount'); //在這裏獲取ajax數據,componentDidMount只執行一次 this.init(this.props); } init = (props)=>{ //存放ajax接口 } //一個組件要從父組件接受參數 ////只要父組件的render函數被從新執行了,子組件的這個生命週期函數就會被執行 //////只要父組件的render函數被執行了,子組件的這個componentWillReceiveProps函數就會被執行 //若是這個組件第一次存在於父組件中,不會執行 //若是這個組件以前已經存在於父組件中,纔會執行 //對於頂層組件不會執行這個生命週期函數 componentWillReceiveProps(){ console.log('child componentWillReceiveProps'); } //組件須要更新嗎,返回的是一個Boolean值,若是返回true,componentWillUpdate、 render、componentDidUpdate 會執行,若是返回false不會執行componentWillUpdate、 render、componentDidUpdate函數 //組件跟新以前,他會被自動執行 //接下來props變化成什麼樣,接下來state會變化成什麼樣 shouldComponentUpdate(nextProps,nextState){ console.log('shoundComponentUpdate'); //接收的props不等於當前的props時會從新渲染,不然不會,提高了性能 if(nextProps.content !==this.props.content){ return true; } else{ return false; } } //當shouldComponentUpdate返回true時,在從新渲染以前(render)以前會被執行 //組件跟新以前,他會自動執行,可是他會在shouldComponentUpdate以後被執行 //若是shouldComponentUpdate返回true它才執行 //若是shouldComponentUpdate返回false就不會執行了 componentWillUpdate(){ console.log('componentWillUpdate'); } //當shouldComponentUpdate返回true時,在從新渲染以後(render)以後會被執行 componentDidUpdate(){ console.log('componentDidUpdate') } //當這個組件即將被從頁面中剔除的時候,會被執行 componentWillUnmount(){ console.log('componentWillUnmount'); } handelInput = (e)=>{ console.log(e.target.value); //調用setState改變state的值就是更新組建的內容,render從新執行,用最新的數據渲染出模板 this.setState({inputValue:e.target.value}); } addItem =()=>{ const {list,inputValue} = this.state; this.setState({list:[...list,inputValue],inputValue:''}) } removeItem = (index)=>{ console.log(index); const {list,inputValue} = this.state; let newList = list; newList.splice(index,1); this.setState({list:newList}); } //數據(props 或者state)發生改變的時候,會被執行 //父組件的render執行後,子組件的render函數也會被執行 //render函數是組件中必須有的生命週期函數,由於這個組件是繼承Copmonent組件,react這個組件內置默認了全部的生命週期函數,除了render沒有內置。 render(){ console.log('render'); const {list} = this.state; return ( <Fragment> <input onChange={this.handelInput} value={this.state.inputValue}/> <button onClick={this.addItem}>提交</button> <ul> { list.map((item,index)=>{ return <li key={index} onClick={()=>this.removeItem(index)}>{item}</li> }) } </ul> </Fragment> ) } } export default Note;//在同一個方法中屢次使用setState,setState會被合併執行,對於相同屬性的設置會保留最後一次設置