2017-07-25 114 views
1

我正在嘗試將GSAP與React一起使用,我遇到了我的動畫被取消的情況。React生命週期事件取消GSAP動畫

我的組件是一個側邊欄,只有當狀態中的'show'屬性爲true時纔會出現。在組件內部,我的主要職責是:

shouldComponentUpdate(nextProps, nextState) { 
    return nextState.show !== this.state.show; 
} 

componentWillUpdate(nextProps, nextState) { 
    if (nextState == true) { 
    // animate the sidebar in 
    } else { 
    // animate the sidebar out 
    } 
} 

toggleSidebar() { 
    const newState = !this.state.show; 
    this.setState({ show: newState }) 
} 

出於某種原因,當我點擊我的按鈕來觸發toggleSidebar功能,側邊欄開始在動畫,然後立即動畫出來。

我有一種感覺,因爲componentWillUpdate返回得太快,但我不確定。

此時,我正考慮使用TransitionGroup並在componentWillEnter/componentWillLeave生命週期掛鉤中包含GSAP動畫代碼,以便它們可以正常工作,但我很好奇是否有任何方法可以解決此問題。

+0

總是使用*如果可能,*會*會有一些令人討厭的副作用。 – Solo

回答

0

一個常見原因是toggleSidebar被調用兩次。 Safari瀏覽器有時會發生這種情況,但我也在Chrome瀏覽器中看到了一些情況。您可以嘗試在按鈕點擊的接收事件上使用e.preventDefault,或使用舊時尚布爾標誌,例如

toggleSidebar() { 
    if (isAnimating) { 
     isAnimating = !isAnimating; 
     return; 
    } 
    isAnimating = true; 
    const newState = !this.state.show; 
    this.setState({ 
     show: newState 
    }) 
} 
+0

嗯,我試過這兩種方法和控制檯從toggleMenu登錄,它似乎只是被調用一次。 –