React+ANTD項目使用後的一些關於生命週期比較實用的心得

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

必定先寫super  能夠接收從父組件傳來的值ajax

父組件往子組件傳值的方法服務器

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

直接在組件中寫屬性名等於屬性值就能夠,有多少傳多少異步

在子組件 ChildComponent 中獲取父組件傳來的值只須要用this

this.props.nextValue

就能夠獲得父組件傳來的值spa

由此衍生一個問題,子組件如何給父組件傳值code

首先,須要在父組件定義一個方法(agechange),而後將方法傳給子組件,component

class App extends Component {
  agechange=(age)=>{
    alert(age)
  }
  
  render() {
    
    return (
      <div className="App">
        <Child agechange={this.agechange}/> //將方法傳給子組件
      </div>
    )
  }
}

在子組件中調用這個方法,將須要傳給父組件的值,經過這個方法傳給父組件,blog

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方法不會觸發重渲染class

3.componentDidMount

 

通常的從後臺(服務器)獲取的數據,都會與組件上要用的數據加載有關,因此都在componentDidMount方法裏面做 

 

4.componentWillReceiveProps

當父組件傳給子組件的props發生改變時,子組件能夠經過componentWillReceiveProps 方法接收,能夠setState 從新渲染組件
當父組件經過ajax異步獲取的值須要傳給子組件時,子組件能夠用到componentWillReceiveProps(nextProps)





於setState() 它不是同步的,也不能說是異步的,因此不要在setState以後,直接用state中的值,很容易出錯。
相關文章
相關標籤/搜索