【问题标题】:How to use timers in React hook?如何在 React 钩子中使用计时器?
【发布时间】:2020-02-02 20:41:10
【问题描述】:

我正在使用 react-native 开发一个应用程序,并且我正在尝试为其启动屏幕设置动画。我想在 3 秒后导航到下一个屏幕。我想知道如何将计时器(如 setTimeOut())与像 useEffect() 这样的反应钩子一起使用。这是我的代码:

const SplashScreen = props => {
    const opacityVal = new Animated.Value(0);
    const fadeAnime = () => {
        Animated.timing(opacityVal, {
            toValue: 1,
            duration: 2000,
            useNativeDriver: true,
        }).start()
    }
    let timer = setTimeout(() => props.navigation.navigate({ routeName: 'UserAuthenication'}), 2000);

    useEffect(fadeAnime, [opacityVal]);
    useEffect(()=>{
        return(() => clearTimeout(timer))
    }, []);
    return(
        <View style={styles.MainContainer}>
           <Animated.View style={{opacity: opacityVal}}>
              <TouchableOpacity style={styles.AnimeContainer}>
                 <Image source={require('../Pics/SplashScreenPic.jpg')} style={styles.ImageContainer}/>
              </TouchableOpacity>
           </Animated.View>
        </View>

    );
};

我试图做这样的工作,因为它在代码中很明显,但它没有工作:

let timer = setTimeout(() => props.navigation.navigate({ routeName: 'UserAuthenication'}), 2000);
 useEffect(()=>{
        return(() => clearTimeout(timer))
    }, []);

【问题讨论】:

    标签: react-native react-hooks


    【解决方案1】:

    useEffect 调用中移动计时器:

    useEffect(() => {
      const timer = setTimeout(() => props.navigation.navigate({ routeName: 'UserAuthenication'}), 2000);
      return(
        () => clearTimeout(timer)
      )
    }, [props.navigation]);
    

    【讨论】:

    • 你能详细说明,发生了什么吗?你是什​​么意思它没有工作?
    • 动画完成后,应用应该导航到下一个屏幕。但它没有发生。
    猜你喜欢
    • 1970-01-01
    • 2021-09-29
    • 2023-03-07
    • 2022-08-19
    • 1970-01-01
    • 2020-07-22
    • 2021-06-30
    • 2021-04-04
    • 1970-01-01
    相关资源
    最近更新 更多