React应用在初始化和更新的过程当中,会通过一系列的逻辑,React在不一样的逻辑时期会执行不一样的生命周期函数,用来给咱们作一些处理。babel
这几个生命周期函数的用法以下:函数
对于componentWillMount和componentDidMount来讲它们是没有参数的,并且一个组件挂载时只会执行一次。测试
举个栗子,需求:定义了两个组件:App组件和Person组件,App组件引用了Person组件而且传入了一个名为no的props,另外在App组件和Person组件内都定义了一个button按钮,分别用于修改Person组件的props和state变化,另外咱们在Person组件内分别定义了上面讲解到的4个生命周期函数,代码以下:this
<div id="root"></div> <script type="text/babel"> class Person extends React.Component{ //定义一个子组件Person constructor(props){ super(props); this.state = {no:props.no+100} } componentWillMount(){ console.log('trigger:componentWillMounted'); } componentDidMount(){ console.log('trigger:componentDidMount'); } componentWillUpdate(newProps,newState){ console.log('trigger:componentDidMount newprops=',newProps,' newState=',newState) } componentDidUpdate(newPros,newState){ console.log('trigger:componentDidUpdate'); } render (){ return <div> <button onClick={e=>this.setState({no:this.state.no+1})}>子组件按钮(用于修改state)</button> <p>props.no:{this.props.no}</p> <p>state.no:{this.state.no}</p> </div> } } class App extends React.Component{ //定义一个父组件App,它会引用子组件,而且修改子组件的props constructor(props){ super(props) } state = {no:1} render(){ return <div> <button onClick={e=>this.setState({no:this.state.no+1})}>父组件按钮(用于修改props)</button> <Person no={this.state.no} /> </div> } } ReactDOM.render(<App/>,root) </script>
最终页面渲染以下:spa
初始化时控制台打印以下:code
表示在Person组件加载过程当中分别触发了componentWillMount和componentDidMount生命周期函数,由于咱们在Person组件就打印了这两个信息,而后咱们点击第一个按钮,看看输出信息:component
writer by:大沙漠 QQ:22969969blog
父组件的按钮对应的事件是每次点击时传递的no递增1,咱们可在Person组件内的componentWillUpdate内打印了newProps,能够看到no发生了变化,每点击一次,componentWillUpdate触发一次,而且Person组件的props.no递增了1。生命周期
同理,咱们点击一下第二个按钮,会触发Person组件的事件,会修改Person组件的state,并触发从新渲染,以下:事件
一样的,点击后也触发了Person组件内的componentWillUpdate生命周期函数,将新的props和state打印了出来,咱们能够看到state发生了变化。
ComponentWillUpdate的第三个参数是context发生变化时新的context的值,有兴趣的本身写个demo测试一下就行了,我就不贴了。
对于这四个生命周期函数来讲,咱们只能在事件触发收作一些与主线无关的操做,什么是主线无关呢,好比componentWillUpdate是React将要更新的时候触发的,我可不能够返回false,这样React就不会继续更新,而是中止下来了呢,React也提供了这样的生命周期函数,叫作shouldComponentUpdate生命周期函数,固然React还有其它的一些生命周期函数,咱们一个个讲解。