React Native - 如何每 x 毫秒重新渲染一个组件? "this.setState is not a function?"

React Native - how to re render a component every x milliseconds? "this.setState is not a function?"

好的,我正在尝试每 x 毫秒更新一次组件的属性 and/or 文本。我深入研究了 https://www.npmjs.com/package/react-interval-renderer 之类的东西,但是我遇到了与 s.

有关的错误

我现在只看 但是我无法将其格式化为我的文件。

我有:

export default props => {
  let [fontsLoaded] = useFonts({
    'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
  });

  this.state ={
   color: "#fff",
   colorAnimTime: 36000,
   time: 0
  }

    setInterval(() => {
      this.setState({
        time: new Date().getMilliseconds()
      });
    }, 1000);


//------------------------------------------------------------------->
  if (!fontsLoaded) {
    return <AppLoading />;
  } else {

    const styles = StyleSheet.create({
      container: { flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
    },
      textWrapper: {
        height: hp('70%'), // 70% of height device screen
        width: wp('80%'),   // 80% of width device screen
        justifyContent: 'center',
        alignItems: 'center',
      },
      myText: {
        fontSize: hp('5.5%'), // End result looks like the provided UI mockup
        fontFamily: 'SequelSans-BlackDisp'
      }
    });

      return (
        <AnimatedBackgroundColorView
        color='#00acdd'
        delay={0.5}
        duration={36000}
        initialColor={this.state.color}
        style={styles.container}>
          <View style={styles.textWrapper}>
            <Text style={styles.myText}>COLOR</Text>
          </View>
        </AnimatedBackgroundColorView>
      );
  }

引用的答案使用 componentDidMount() { 来包含 setInterval,但是如果我将它放在我当前拥有 setInterval

的位置,我会得到语法错误

现在我得到

this.setState is not a function

并尝试将 setInterval 绑定到右侧 this 但我相信我不明白如何设置我的文件。

1000 毫秒后,我想更改 <AnimatedBackgroundColorView> 的 'color' 并重新加载组件。 (所以它再次动画 - https://www.npmjs.com/package/react-native-animated-background-color-view

我该怎么做?

您的组件是作为功能组件编写的,而不是 class。要创建有状态的功能组件,您需要使用钩子setState。您收到此错误是因为组件上没有对象 属性 setStatethis。您还需要使用 useEffect 挂钩来设置间隔。

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

import React, { useState } from 'react';

export default props => {
  let [fontsLoaded] = useFonts({
    'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
  });

  const color = "#fff";
  const colorAnimTime = 36000;
  const [time, setTime] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setTime(new Date().getMilliseconds));
    }, 1000);
    return () => clearInterval(interval);
  }, []);


//------------------------------------------------------------------->