在 React Native 启动画面中显示 ActivityIndi​​cator 5 秒

Show ActivityIndicator 5 seconds in react native splash screen

我想在此启动画面中显示 Activity 指示符至少 5 秒。我尝试了 setTimeOut 方法,但它不起作用。它很快消失并显示此警告。

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. at src/screens/SplashScreen.js:15:15 in setTimeout$argument_0

这是我的代码,我该如何解决这个问题?

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, View } from 'react-native';

const SplashScreen = () => {
  const [animate, setAnimate] = useState(true);

  useEffect(() => {
    closeActivityIndicator();
  }, []);

  const closeActivityIndicator = () => {
    setTimeout(() => {
      setAnimate(false);
    }, 5000);
  };

  return (
    <View
      style={{ flex: 1, justifyContent: 'center', backgroundColor: '#06bcee' }}
    >
      <ActivityIndicator animating={animate} size="large" color="#ffffff" />
    </View>
  );
};

export default SplashScreen;

我看不到你的导航函数调用在哪里。无论如何,您可以做的是将 animate 状态保持为 true,activity 指示器正在动画并不重要。我看到的另一个问题是您的组件已卸载,但您的 setTimout() 没有被清除,因此它会不断更新您的状态。你可以这样做。

const timerRef = React.useRef(null) // you can also import useRef() directly from 'react'

useEffect(() => {
  timerRef.current = setTimeout(() => {
    // code for navigation
  }, 5000);
  
  return () => clearTimeout(timerRef.current);
}, []);