React生命周期

大兔子大兔子 提交于 2019-12-27 07:29:16




<!DOCTYPE html>    
<html>    
<head>    
<meta charset="UTF-8" />    
<title>React生命周期</title>    
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>    
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>    
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>    
</head>    
<body>    
<div id="root"></div>    
<script type="text/babel">    
class Components extends React.Component {

  constructor(props){
    super(props);
    this.state = {}
  }
  componentWillMount(){
    console.log("实例化:componentWillMount")
  }
  componentDidMount(){
    console.log("实例化:componentDidMount")
  }
  componentWillReceiveProps(){
    console.log("存在期:componentWillReceiveProps")
  }
  shouldComponentUpdate(nextProps,nextState){
    console.log("存在期:shouldComponentUpdate",nextProps,nextState)
    return true;
  }
  componentWillUpdate(){
    console.log("存在期:componentWillUpdate")
  }
  componentDidUpdate(){
    console.log("存在期:componentDidUpdate")
  }
  render() {
    if(!this.props.reRender){
      console.log("实例化:render")
    }else{
      console.log("存在期:render")
    }
    return (
      <div>
        <br />
        请查看下面的console
        <br />
      </div>
    )

  }
}
Components.defaultProps = {
    text: "hello word",
}
class App extends React.Component{
  constructor(props){
    super(props);
    this.state = {}
  }
  refresh(){
    return (e)=>{
      this.setState({
        reRender: true,
      })
    }
  }
  render(){
    return (
      <div>
        <Components reRender={this.state.reRender}/>  
        <button onClick={this.refresh()}>
            更新Component
        </button>
      </div>
    )
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>    
</body>    
</html>    





易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!