react学习系列之组件生命周期
状态组件的生命周期可分成三个状态:
方法生命周期的API有:
实例化当组件在客户端被实例化,第一次被创建时,以下方法依次被调用:
当组件在服务端被实例化,首次被创建时,以下方法依次被调用:
componentDidMount 不会在服务端被渲染的过程中调用。 存在期此时组件已经渲染好并且用户可以与它进行交互,比如鼠标点击,手指点按,或者其它的一些事件,导致应用状态的改变,你将会看到下面的方法依次被调用
示例通过以下示例可以看到过程中调用的方法 import React from 'react'; import ReactDOM from 'react-dom'; class Button extends React.Component { constructor(props) { super(props); console.log('init'); this.state = { data : 0 } } setNewNumber = () => { this.setState({ data : this.state.data + 1 }) } render() { return ( <div> <button onClick = {this.setNewNumber}>insert</button>,<Content myNumber = {this.state.data}/> </div> ) } } class Content extends React.Component { constructor(props) { super(props); this.state = { opacity: props.opacity || 1 } } componentWillMount() { console.log('Component WILL MOUNT!') } componentDidMount() { console.log('Component DID MOUNT!') } componentWillReceiveProps = (newProps) => { console.log('Component WILL RECIEVE PROPS!') } shouldComponentUpdate = (newProps,newState) => { return true; } componentWillUpdate = (nextProps,nextState) => { console.log('Component WILL UPDATE!'); } componentDidUpdate = (prevProps,prevState) => { console.log('Component DID UPDATE!') } componentWillUnmount() { console.log('Component WILL UNMOUNT!') } render() { return ( <div> <h1>{this.props.myNumber}</h1> </div> ) } } ReactDOM.render( <Button/>,document.getElementById('lifetime') ); 初始化: 状态变化: 参考资料React/React Native 的ES5 ES6写法对照表 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |