zoukankan      html  css  js  c++  java
  • react 生命周期

    import React from 'react';
    import ReactDOM from 'react-dom';

    //子类

    class SayHello2 extends React.Component{
    constructor(props){
    super(props);
    this.state=({
    word:""
    })
    }
    componentWillReceiveProps(){
    console.log("componentWillReceiveProps clalled")
    }
    shouldComponentUpdate(){
    console.log("shouldComponentUpdate called")
    return true;
    }
    componentWillUpdate(){
    console.log("componentWillUpdate called")
    }
    //this.setState 进入shouldComponentUpdate
    //this.forceUpdate 进入componentWillUpdate
    handleClick(){
      this.setState({
        word:'word changed'
      })
     或 this.state.word="word change";
       this.forceUpdate();
    }
    render(){
    return <div>{this.state.word}{this.props.name}
    <button onClick={this.handleClick.bind(this)}>改变state</button>

    </div>
    }
    }

    //父类
    class SayHello3 extends React.Component{
    constructor(props){
    super(props);
    this.state=({
    word2:'word2'
    })
    this.handleClick = this.handleClick.bind(this);
    }
    componentWillMount(){
    console.log("componentWillMount called")
    }
    componentDidMount(){
    console.log("componentDidMount called")
    }
    componentWillUnmount(){
    console.log("componentWillUnmount called")
    }
    componentUnmountEvent(){
    ReactDOM.render(
    <h1>SayHello3 moved</h1>,
    document.getElementById("root3")
    )
    }
    handleClick(){
    this.setState({
    word2:'word2 changed'
    })
    }
    render(){
    return <h1>
    hello <SayHello2 name={this.state.word2}></SayHello2>----父类中调用子类
    <button onClick={this.handleClick}>改变word2</button>
    <button onClick={this.componentUnmountEvent.bind(this)}>移除</button>
    </h1>
    }
    }
    ReactDOM.render(
    <SayHello3 name="qq11111221" word="word"/>,
    document.getElementById("root3")
    )

    1、父类调用子类 参数变化的时候(本例中是点击“改变word2”),先调用子类中componentWillReceiveProps(),然后调用shouldComponentUpdate(),shouldComponentUpdate()返回的是true 在调用componentWillUpdate()

    2、通过this.setState({})修改变量值(本例中点击“改变state”),先调用shouldComponentUpdate(),然后调用componentWillUpdate()

    3、通过this.forceUpdate() 修改变量,直接调用componentWillUpdate()

  • 相关阅读:
    研发环境容器化实施过程(docker + docker-compose + jenkins)
    Java虚拟机-字节码执行引擎
    Java虚拟机-类加载机制
    Java虚拟机-字节码指令
    Java虚拟机-类文件结构
    Java虚拟机理解-内存管理
    单元测试实践(SpringCloud+Junit5+Mockito+DataMocker)
    Git基础概念与Flow流程介绍
    谷歌最佳实践
    谷歌最佳实践
  • 原文地址:https://www.cnblogs.com/zhangxintong1314/p/6565891.html
Copyright © 2011-2022 走看看