React.js Tutorial: React Component Lifecycle
Introduction about React component lifecycle. 1 LifecycleA React component in browser can be any of the following three statuses: mounted,update and unmounted. So React component lifecycle can be divided into three phases according to these statuses: mounting,updating and unmounting. 2 MountingReact.js exposed interfaces or hook methods in each phase of component lifecycle. 2.1 Initializing stateYou can optionally set initial state value in? const tom_and_jerry = [ { name: ‘Tom‘,score: 55 },{ name: ‘Jerry‘,score: 80 } ]; class ScoreBoard extends React.Component { constructor(props) { super(props); this.state = { players: tom_and_jerry } } // ... } If you are using? var ScoreBoard = React.createClass({ getInitialState: function() { return { players: tom_and_jerry } },// ... }); The? Initialization of state should typically only be done in a top level component,which acts as a role of?controller view?in your page. 2.2 Default propsYou can also define default values of component props (properties) if the parent component does not declare their values. Return default props using? class SinglePlayer extends React.Component { static defaultProps = { name: ‘Nobody‘,score: 0 } // ... } Default props in? class SinglePlayer extends React.Component { // ... } SinglePlayer.defaultProps = { name: ‘Nobody‘,score: 0 } You can define? var SinglePlayer = React.createClass({ getDefaultProps: function() { return { name: ‘Nobody‘,score: 0 } } }); The? 2.3 componentWillMount()The? It is also a good place to set initial state value inside? class SinglePlayer extends React.Component { componentWillMount() { this.setState({ isPassed: this.props.score >= 60 }); alert(‘componentWillMount => ‘ + this.props.name); console.log(‘componentWillMount => ‘ + this.props.name); } // ... } 2.4 componentDidMount()This lifecycle method will be invoked after rendering. It is the right place to access DOM of the component. class ScoreBoard extends React.Component { constructor(props) { super(props); this._handleScroll = this.handleScroll.bind(this); } handleScroll() {} componentDidMount() { alert(‘componentDidMount in NoticeBoard‘); window.addEventListener(‘scroll‘,this._handleScroll); } // ... } 3 Updating3.1 componentWillReceiveProps()void componentWillReceiveProps(object nextProps) This method will be invoked when a component is receiving new props.? class SinglePlayer extends React.Component { componentWillReceiveProps(nextProps) { // Calculate state according to props changes this.setState({ isPassed: nextProps.score >= 60 }); } } The old props can be accessed via? 3.2 shouldComponentUpdate()boolean shouldComponentUpdate(object nextProps,object nextState)
This method is usually an opportunity to prevent the unnecessary rerendering considering performance. Just let? class SinglePlayer extends React.Component { shouldComponentUpdate(nextProps,nextState) { // Don‘t rerender if score doesn‘t change,if ( nextProps.score == this.props.score ) { return false; } return true; } } 3.3 componentWillUpdate()void componentWillUpdate(object nextProps,object nextState) Invoked just before? Use this as an opportunity to prepare for an update. class SinglePlayer extends React.Component { componentWillUpdate(nextProps,nextState) { alert(‘componentWillUpdate => ‘ + this.props.name); console.log(‘componentWillUpdate => ‘ + this.props.name); } } 3.4 componentDidUpdate()void componentDidUpdate(object prevProps,object prevState) Invoked immediately after the component‘s updates are flushed to the DOM. This method is not called for the initial rendering. You can perform DOM operations after an update inside this function. class SinglePlayer extends React.Component { componentDidUpdate(prevProps,prevState) { alert(‘componentDidUpdate => ‘ + this.props.name); console.log(‘componentDidUpdate => ‘ + this.props.name); } } 4 Unmountingvoid componentWillUnmount() This is invoked immediately before a component is unmounted or removed from the DOM. Use this as an opportunity to perform cleanup operations. For example,unbind event listeners here to avoid memory leaking. class ScoreBoard extends React.Component { componentWillUnmount() { window.removeEventListener(‘scroll‘,this._handleScroll); } } 5 Sample codesComplete sample codes to log each lifecycle method call in browser‘s console. https://www.codevoila.com/post/57/reactjs-tutorial-react-component-lifecycle<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>React Component Lifecycle Demo</title> <!-- react includes two parts: react.js and react-dom.js --> <script src="//fb.me/react-15.2.1.js"></script> <script src="//fb.me/react-dom-15.2.1.js"></script> <!-- babel standalone --> <script src="//cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.10.3/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const tom_and_jerry = [ { name: ‘Tom‘,score: 55 },{ name: ‘Jerry‘,score: 80 } ]; class SinglePlayer extends React.Component { constructor(props) { super(props); this.state = { isPassed: false } } componentWillMount() { // Mark it as ‘Pass‘ if score >= 60 this.setState({ isPassed: this.props.score >= 60 }); console.log(‘componentWillMount => ‘ + this.props.name); alert(‘componentWillMount => ‘ + this.props.name); } componentDidMount() { console.log(‘componentDidMount => ‘ + this.props.name); alert(‘componentDidMount => ‘ + this.props.name); } componentWillReceiveProps(nextProps) { // Calculate state according to props changes this.setState({ isPassed: nextProps.score >= 60 }); console.log(‘componentWillReceiveProps => ‘ + this.props.name + ‘: ‘ + nextProps.score); alert(‘componentWillReceiveProps => ‘ + this.props.name + ‘: ‘ + nextProps.score); } shouldComponentUpdate(nextProps,nextState) { // Don‘t rerender if score doesn‘t change,if ( nextProps.score == this.props.score ) { console.log(‘shouldComponentUpdate => ‘ + this.props.name + ‘? false‘); alert(‘shouldComponentUpdate => ‘ + this.props.name + ‘? false‘); return false; } console.log(‘shouldComponentUpdate => ‘ + this.props.name + ‘? true‘); alert(‘shouldComponentUpdate => ‘ + this.props.name + ‘? true‘); return true; } componentWillUpdate(nextProps,nextState) { console.log(‘componentWillUpdate => ‘ + this.props.name); alert(‘componentWillUpdate => ‘ + this.props.name); } componentDidUpdate(prevProps,prevState) { console.log(‘componentDidUpdate => ‘ + this.props.name); alert(‘componentDidUpdate => ‘ + this.props.name); } componentWillUnmount() { console.log(‘componentDidUpdate => ‘ + this.props.name); alert(‘componentDidUpdate => ‘ + this.props.name); } render() { console.log("render => " + this.props.name); return ( <div> <h5><span>Name: </span>{this.props.name}</h5> <p><span>Score: </span><em>{this.props.score}</em></p> <p><span>Pass: </span><input type="checkbox" defaultChecked={this.state.isPassed} disabled={true} /></p> </div> ); } } class ScoreBoard extends React.Component { constructor(props) { super(props); this.state = { players: tom_and_jerry }; } changeScore(amount) { if ( typeof(amount) != "number" ) { return; } let players = this.state.players; let tom = players[0]; tom.score = tom.score + amount; tom.score = (tom.score > 100) ? 100 : tom.score; tom.score = (tom.score < 0) ? 0 : tom.score; players[0] = tom; this.setState({ players: players }); } render() { return ( <div> <h4>Score Board</h4> <div> <button onClick={ (amount) => this.changeScore(5) }>Score of Tom: +5</button> <button onClick={ (amount) => this.changeScore(-5) }>Score of Tom: -5</button> </div> { this.state.players.map((v,idx) => { return <SinglePlayer key={idx} name={v.name} score={v.score} /> }) } </div> ); } } class App extends React.Component { render() { return ( <div> <h1>React Component Lifecycle Demo</h1> <ScoreBoard /> </div> ) } } // Mount root App component ReactDOM.render(<App />,document.getElementById(‘app‘)); </script> </body> </html> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- react如何兼容IE8
- ios – 非公共API使用:不允许应用访问UDID,也不得使用UIDe
- c# – 如何使用AutoMapper将MySQL时间戳保存为String而不是
- c# – .NET Standard 1.6中的System.Threading.Tasks.Paral
- xml – 使用xpath获取节点的第N个子节点
- PostgreSQL安装和简单使用(转载:http://www.linuxsir.org
- PostgreSQL Role Management
- c# – Dynamics Crm:获取statuscode / statecode映射的元数
- Vue 进阶教程之v-model详解
- react实践之 redux react-redux