从useEffect()钩子调用时layoutAnimation不起作用

时间:2020-07-24 19:36:50

标签: reactjs react-native

我正在尝试从useEffect()挂钩触发动画,它具有依赖性,因此不会循环播放。

在useEffect内部被称为

const toggleDrawerAnimation=()=>{
        console.log('started next animation')
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
        setDrawerPosition(drawerPosition === "bottom" ? "top" : "bottom")
};

// and a snippet of my drawer component
<View style={[styles.optionsMenuContainer,drawerPosition === "bottom"? null: styles.fading ]}>

动画确实有效,但是是即时的。
我尝试调用相同的代码,但是使用buttonPress而不是useEffect(),它的动画效果很流畅。

这一直在踢我的屁股。 有什么问题?谢谢您的帮助。

编辑:这是我的useEffect代码块

    useEffect(()=>{
        if (init){
            console.log('first render')
            setInit(false)
        }
        else{
            console.log('second render')

            toggleDrawerAnimation()

        }
    },[init])

2 个答案:

答案 0 :(得分:1)

您可以使用LayoutEffect来实现这一点,正如其他海报所提到的,问题是useEffect在UI绘制后触发。

https://reactjs.org/docs/hooks-reference.html#uselayouteffect

答案 1 :(得分:0)

由于 useEffect 回调在渲染提交阶段之后被调用,因此在渲染周期之后被调用,LayoutAnimation.configureNext 意味着“准备”下一个 em> 渲染,在 useEffect 内部调用它已经太晚了。

遗憾的是,目前没有解决此问题的方法,因为 useEffect 是唯一用于与组件生命周期相关联的钩子。

更多信息:https://daveceddia.com/react-hook-after-render/#:~:text=Can%20you%20run%20a%20hook,it%20also%20runs%20after%20render)。