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中的值,很容易出错。





  • 相关阅读:
    怎样通过iPhone Safari 来安装测试版ipa
    UINavigationController检测后退按钮被按下
    Android系统在超级终端下必会的命令大全(adb shell命令大全)
    so 加载符号找不到的问题解决
    Ubuntu Android 开发jdk1.5和1.6之间的切换
    UIView animation
    HTC G11 获取Root权限图文教程
    Android.mk文件语法规范
    Android NDK 下的宽字符编码转换及icu库的使用
    [转载].NET制作安装卸载程序 Virus
  • 原文地址:https://www.cnblogs.com/cherishli/p/8963323.html
Copyright © 2011-2022 走看看