美文网首页
react 生命周期

react 生命周期

作者: 如此行走 | 来源:发表于2021-08-31 14:54 被阅读0次

    (react 生命周期图----github)[https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/]
    (官方实例)[https://zh-hans.reactjs.org/docs/react-component.html]

    本地测试代码,包含react 16.4 版本的所有生命周期:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <style>
        .list{
          width: 200px;
          height: 150px;
          background-color: skyblue;
          overflow:auto;
        }
        .news{
          height: 30px;
        }
      </style>
    </head>
    <body>
      <div id="test"></div>
      <!-- 引入react核心库 -->
      <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
      <!-- 用于支持react操作DOM -->
      <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
      <!-- 用于将jsx转为js -->
      <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
      
      <script type="text/babel">
        class Weather extends React.Component{
          constructor(props){
            super(props)
            this.state = {
              date: '今天',
              weather: '风和日丽',
              opacity:1,
              newsArr: []
            }
            console.log('constructor');
          }
          // 初始挂载及后续更新时都会被调用 返回一个对象来更新 state,如果返回 null 则不更新任何内容。
          static getDerivedStateFromProps(props, state){
            console.log('getDerivedStateFromProps');
            return {date: '前天'}
          }
          //控制组件更新的”阀门“,不写时默认调用返回true   nextState 修改后的值
          shouldComponentUpdate(nextProps, nextState){
            console.log('shouldComponentUpdate');
            return nextState.opacity > 0.8
          }
          //组件挂载完毕
          componentDidMount(){
            console.log('componentDidMount');
            // this.timer=setInterval(()=>{
            //   //获取原状态
            //   let {opacity}=this.state;
            //   //修改状态
            //   opacity-=0.1;
            //   if(opacity<=0) opacity=1;
            //   //设置新的状态
            //   this.setState({opacity})
            // },1200)
          }
          // 最近一次渲染输出(提交到 DOM 节点)之前调用
          getSnapshotBeforeUpdate(prevProps, prevState){
            console.log('getSnapshotBeforeUpdate');
            let height=this.refs.list.scrollHeight;
            return height;
          }
          // 组件更新完毕后执行
          componentDidUpdate(preProps,preState,height){
            console.log('componentDidUpdate');
            // 滚动高度逐次添加
            this.refs.list.scrollTop+=this.refs.list.scrollHeight-height;
          }
          //组件将要卸载
          componentWillUnmount(){
            console.log('componentWillUnmount');
            //清除定时器
            clearInterval(this.timer)
          }
          death=()=>{
            //卸载组件
            ReactDOM.unmountComponentAtNode(document.getElementById('test'))
          }
          //强制更新按钮的回调
          force=()=>{
            //强制更新组件,不用进过阀门
            this.forceUpdate()
          }
          changeOpacity = ()=>{
              //获取原状态
              let {opacity}=this.state;
              //修改状态
              opacity-=0.1;
              if(opacity<=0) opacity=1;
              //设置新的状态
              this.setState({opacity})
          }
          addNews = ()=>{
             //获取原状态
             const {newsArr}=this.state;
              //模拟一条新闻
              let news='新闻'+(newsArr.length+1);
              //更新状态
              this.setState({newsArr:[news,...newsArr]});
          }
          render(){
            console.log('render');
            const {newsArr, opacity, date, weather}=this.state;
            return (
              <div>
                <h1 style={{opacity}} onClick={this.death}>{date}天气不错,挺{weather}的</h1>
                <button onClick={this.force}>强制刷新</button>
                <button onClick={this.changeOpacity}>改变opacity</button>
                
                <div className='list' ref='list'>
                {
                  newsArr.map((item,index)=>{
                    return <div key={index} className='news'>{item}</div>
                  })
                }
              </div>
              <button onClick={this.addNews}>添加新闻</button>
            </div>
            )
          }
        }
        ReactDOM.render(<Weather/>,document.getElementById('test'))
      </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:react 生命周期

          本文链接:https://www.haomeiwen.com/subject/uceoiltx.html