zoukankan      html  css  js  c++  java
  • React+ANTD项目使用后的一些关于生命周期比较实用的心得

    1.  constructor()
    constructor(props){
       super(props)
      this.state=({
       })    
    }
    
    

    一定先写super  可以接收从父组件传来的值

    父组件往子组件传值的方法

    <ChildComponent  nextValue={xxx.xxx} nextValue2={xxx.xxx}/>

    直接在组件中写属性名等于属性值就可以,有多少传多少

    在子组件 ChildComponent 中获取父组件传来的值只需要用

    this.props.nextValue

    就可以得到父组件传来的值

    由此衍生一个问题,子组件如何给父组件传值

    首先,需要在父组件定义一个方法(agechange),然后将方法传给子组件,

    class App extends Component {
      agechange=(age)=>{
        alert(age)
      }
      
      render() {
        
        return (
          <div className="App">
            <Child agechange={this.agechange}/> //将方法传给子组件
          </div>
        )
      }
    }

    在子组件中调用这个方法,将需要传给父组件的值,通过这个方法传给父组件,

    class Child extends Component {
        constructor(props){
            super(props)
            this.state=({
                age:0
            })
        }
        handleChange=()=>{
            this.setState({
                age:this.state.age+3
            })
            this.props.agechange(this.state.age) //将子组件的age值传给父组件
        }
        render(){
            return(
                <div>
                    <button onClick={this.handleChange.bind(this)}>点击增加age</button>
                </div>
            )
        }
    }

    2.componentWillMount

       关于componentWillMount方法只想说一点,它的调用在constructor之后,在render之前,在这方法里的代码调用setState方法不会触发重渲染

    3.componentDidMount

    一般的从后台(服务器)获取的数据,都会与组件上要用的数据加载有关,所以都在componentDidMount方法里面作 

    4.componentWillReceiveProps

    当父组件传给子组件的props发生改变时,子组件可以通过componentWillReceiveProps 方法接收,可以setState 重新渲染组件
    当父组件通过ajax异步获取的值需要传给子组件时,子组件可以用到componentWillReceiveProps(nextProps)





    于setState() 它不是同步的,也不能说是异步的,所以不要在setState之后,直接用state中的值,很容易出错。





  • 相关阅读:
    Java链接 Oracle11g R2
    MARS3.6 Programming
    相关分析
    统计学中的P值与显著性的意义
    Java的输入/输出操作
    SQL Server数据类型一览表
    Fragstats:使用R软件读取frag78b.asc文件
    收藏一下大牛的数据挖掘学习经验
    数据库系统概论(第四版)习题解答
    ArcGIS中的坐标系统定义与投影转换
  • 原文地址:https://www.cnblogs.com/cherishli/p/8963323.html
Copyright © 2011-2022 走看看