1. 程式人生 > 其它 >中props使用this報錯_React子元件props狀態更新前後對比

中props使用this報錯_React子元件props狀態更新前後對比

技術標籤:中props使用this報錯

df46a867e1f257aadc8ad31cb378451e.png
使用生命週期:getDerivedStateFromProps和componentDidUpdate
(getDerivedStateFromProps前身componentWillReceiveProps)

1、首先在當前元件獲取父元件通過props傳入的狀態

this.state = {
     visible: this.props.visible,
}
//當前元件,我們通過state取父元件的props

2、當props發生改變時getDerivedStateFromProps執行,將改變後的props更新到當前state

static getDerivedStateFromProps(nextProps, prevState) {
        //該方法內禁止訪問this
        if (nextProps.visible !== prevState.visible) {
            //通過對比nextProps和prevState,返回一個用於更新狀態的物件
            return {
                visible: nextProps.visible
            }
        }
        //不需要更新狀態,返回null
        return null
}
此時的this.state已得到發生改變後的props實時賦值,this.state.visible為最新狀態,不再通過this.props取

3、如在狀態更新後需要做一些操作,而getDerivedStateFromProps不允許使用this,導致操作困難,解決辦法componentDidUpdate

 componentDidUpdate(prevProps) {
//通過prevProps和更新後的state做前後對比,得到同getDerivedStateFromProps的效果
        if (prevProps.visible !== this.state.visible) {
        //這裡是你要做的操作
            if (this.state.visible) {
                this.setTIme()
            }
        }
    }

這套方法是我在做拖動封裝的時候使用到,由於拖動封裝只是一個殼子,需要將內容放到拖動元件中,這裡就涉及到state和props的前後更新,且拖動封裝是符合條件才渲染,否則不進行DOM渲染。當操作拖動封裝中的內容會使父元件state更新props跟著更新,使得拖動封裝會重新位置定位計算,即使他們狀態一致。所以需要以上操作,防止this.setTIme()被重新計算。