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()

  • 相关阅读:
    装饰器 如何理解Python装饰器?
    python装饰器详解
    window 10下安装jdk
    Linux中pam认证详解(上)
    VMware/KVM/OpenStack虚拟化之网络模式总结
    java问题排查命令
    今日面试问题
    Qwtplot3D Qt5.12.0 MinGW 编译运行
    20212022年寒假学习进度06
    Springboot笔记<10>常用注解总结
  • 原文地址:https://www.cnblogs.com/zhangxintong1314/p/6565891.html
Copyright © 2011-2022 走看看