什么是生命周期函数:在某一时刻组件会自动调用执行的函数。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会被合并执行,对于相同属性的设置会保留最后一次设置