React生命周期函数
react生命周期函数可以分为三个阶段:挂载阶段(Mounting),更新阶段(Updating),卸载阶段(Unmounting)
挂载阶段(Mounting)
1.constructor
2.componentWillMount
3.render
4.componentDidMount
更新阶段(Updating)
一,props发生变化
1.componentWillReceiveProps
2.shouldComponentUpdate
3.componentWillUpdate
4.render
5.componentDidUpdate
二,state发生变化,props没有发生变化
1.shouldComponentUpdate
2.componentWillUpdate
3.render
4.componentDidUpdate
卸载阶段(Unmounting)
1.componentWillUnmount
----------------------------------------------------
自己想写一个显示时间的组件
class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { console.log('componentDidMount'); this.setState({ date: new Date() }); } render() { console.log('render'); return ( <div> <h1>Hello , World</h1> <h2>Now is {this.state.date.toLocaleTimeString()}</h2> </div> ); } } //setInterval(changTime,1000); ReactDOM.render( <Clock/>, document.getElementById('example') );
我开始的思路是因为componentDidMount会在组件挂载之后执行,然后在哪里更新state从而render也会执行,那么时间就自然的更新了,
可惜还是自己太年轻了,其实componentDidMount只会在组件挂载后执行,且只会执行一次,哈哈,所以错了
发现控制台就输出
render
componentDidMount
render
然后就什么都没有了,时间还是不会改变