談談React--componentWillReceiveProps的使用

什麼是componentWillReceiveProps?

componentWillReceiveProps是React生命週期中的一個環節,有關React的生命週期,同窗們能夠在這裏詳細瞭解。css

componentWillReceiveProps在初始化render的時候不會執行,它會在Component接受到新的狀態(Props)時被觸發,通常用於父組件狀態更新時子組件的從新渲染。這個東西十分好用,可是一旦用錯也會形成十分嚴重的後果。html

在componentWillReceiveProps這個回調函數中,咱們能夠獲取到就是props,經過this.props來獲取,而後新的props則是經過函數的參數傳入,在這裏咱們能夠比較兩個props從而對本組件的state做出安全的變動而後從新渲染咱們的組件或者是觸發子組件內的某些方法。react

//這種方式十分適合父子組件的互動,一般是父組件須要經過某些狀態控制子組件渲染亦或銷燬...

componentWillReceiveProps(nextProps) {//componentWillReceiveProps方法中第一個參數表明即將傳入的新的Props
    if (this.props.sharecard_show !== nextProps.sharecard_show){
        //在這裏咱們仍能夠經過this.props來獲取舊的外部狀態
        //經過新舊狀態的對比,來決定是否進行其餘方法
        if (nextProps.sharecard_show){
            this.handleGetCard();
        }
    }
}
複製代碼

上面是componentWillReceiveProps經常使用的方式,可是若是使用不當可能會致使如下後果,通常體現爲組件陷入渲染死循環,他會一直接受新的外部狀態致使自身一直在重渲染。安全

componentWillReceiveProps(nextProps) {
    if (this.props.sharecard_show !== nextProps.sharecard_show){
        if (nextProps.sharecard_show){
            this.handleGetCard();
        }
    }
}

handleGetCard() {
    this.props.test()
}

//父組件內

test() {
    this.setState({
        sharecard_show: !this.state.sharecard_show
    })
}
複製代碼

一旦項目中出現這樣的代碼,有很大概率就會陷入死循環,這兩個組件會一直在傳遞狀態而且從新渲染,而後頁面估計就卡掛了。這是其中一個須要注意的地方,另外咱們須要謹記,在componentWillReceiveProps中想做任何變動最好都將兩個狀態進行比較,假如狀態有異才執行下一步。否則容易形成組件的屢次渲染,而且這些渲染都是沒有意義的。函數