參考資料:
React:組件的生命週期
這個文檔利用es5的creatClass,有些陳舊。須要研究二者差異的, 移步
React 生命週期
這個過於粗暴,沒有示例
render()
react最重要的步驟,建立虛擬dom,進行diff算法,更新dom樹都在此進行。此時就不能更改state了。
只能經過 this.props 和 this.state 訪問數據(不能修改),也就是不能調用this.setState()。
只能出現一個頂級組件,不能返回一組元素。例如:html
render(){ //這樣不行 this.setState({ newState:_newState }); return ( <div></div> //去掉下面一行 <div></div> ); }
import React,{Component} from 'react'; import ReactDOM from 'react-dom'; class Clock extends Component{ constructor(props){ super(props); this.state = { date:new Date() } } //渲染前render執行 componentWillMount(){ //this.timer/////////////////////////// this.timer =setInterval(()=>{ this.setState({ date: new Date() }) },1000) } componentDidMount(){ this.clock.focus(); } componentWillUnmount(){ clearInterval(this.timer) } render(){ return( <div> <h1> <p ref={(clock)=>this.clock=clock}>now time:</p> {this.state.date.toLocaleTimeString()} </h1> </div> ) } } ReactDOM.render(<Clock />, document.getElementById('root'));
import React from 'react'; import ReactDOM from 'react-dom'; class Content extends React.Component { constructor(){ super(); this.state = { test:0 } } componentWillMount() { console.log('Component WILL MOUNT!') } componentDidMount() { console.log('Component DID MOUNT!') } componentWillReceiveProps(newProps) { console.log(newProps) console.log('Component WILL RECEIVE PROPS!') } shouldComponentUpdate(newProps, newState) { console.log(newProps,newState) return true; } componentWillUpdate(nextProps, nextState) { console.log(nextProps,nextState) console.log('Component WILL UPDATE!'); } componentDidUpdate(prevProps, prevState) { console.log(prevProps,prevState) console.log('Component DID UPDATE!') } componentWillUnmount() { console.log('Component WILL UNMOUNT!') } _handleClick(){ this.setState({ test:this.state.test + 1 }) } render() { return ( <div> <h3>{this.props.myNumber}</h3> <label onClick={this._handleClick.bind(this)}>點我</label> <span>{this.state.test}</span> </div> ); } } class Button extends React.Component { constructor(props) { super(props); this.state = {data: 0}; this.setNewNumber = this.setNewNumber.bind(this); } setNewNumber() { this.setState({data: this.state.data + 1}) } render() { return ( <div> <button onClick = {this.setNewNumber}>INCREMENT</button> <Content myNumber = {this.state.data}></Content> </div> ); } } ReactDOM.render(<Button />, document.getElementById('root'));