React native - "Отрисовано больше хуков, чем при предыдущей визуализации?" - PullRequest
3 голосов
/ 10 июля 2020

Я столкнулся с этой проблемой только после того, как включил хук useEffect (), как это было предложено React native - «this.setState не является функцией», пытаясь оживить цвет фона?

С следующее, я получаю

Обработано больше хуков, чем при предыдущем рендеринге

export default props => {
      let [fontsLoaded] = useFonts({
        'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
            'SequelSans-RomanDisp' : require('./assets/fonts/SequelSans-RomanDisp.ttf'),
            'SequelSans-BoldDisp' : require('./assets/fonts/SequelSans-BoldDisp.ttf'),
            'SequelSans-BlackDisp' : require('./assets/fonts/SequelSans-BlackDisp.ttf'),
      });
      if (!fontsLoaded) {
        return <AppLoading />;
      } else {
    
    //Set states
      const [backgroundColor, setBackgroundColor] = useState(new Animated.Value(0));

      useEffect(() => {
        setBackgroundColor(new Animated.Value(0));
      }, []);    // this will be only called on initial mounting of component,
      // so you can change this as your requirement maybe move this in a function which will be called,
      // you can't directly call setState/useState in render otherwise it will go in a infinite loop.
      useEffect(() => {
        Animated.timing(this.state.backgroundColor, {
          toValue: 100,
          duration: 5000
        }).start();
      }, [backgroundColor]);

      var color = this.state.colorValue.interpolate({
        inputRange: [0, 300],
        outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
      });

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

      return (
        <Animated.View style={styles.container}>
          <View style={styles.textWrapper}>
            <Text style={styles.myText}>Login</Text>
          </View>
        </Animated.View>
      );
  }
};

Я просто пытаюсь анимировать затухание цвета фона в представлении. Я попытался удалить первый useEffect, если он вызывал некоторую избыточность, но это ничего не дало. Я новичок в ReactNative - что здесь не так?

РЕДАКТИРОВАТЬ:

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

  //Set states
    const [backgroundColor, setBackgroundColor] = useState(new Animated.Value(0));

    useEffect(() => {
      setBackgroundColor(new Animated.Value(0));
    }, []);    // this will be only called on initial mounting of component,
    // so you can change this as your requirement maybe move this in a function which will be called,
    // you can't directly call setState/useState in render otherwise it will go in a infinite loop.
    useEffect(() => {
      Animated.timing(useState(backgroundColor), {
        toValue: 100,
        duration: 7000
      }).start();
    }, [backgroundColor]);

    // var color = this.state.colorValue.interpolate({
    //   inputRange: [0, 300],
    //   outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
    // });

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

    const styles = StyleSheet.create({
      container: { flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: backgroundColor

Новые ошибки:

недопустимый параметр 'color' передан в 'Таблицу стилей'

Анимированный useNativeDriver не указан

1 Ответ

0 голосов
/ 10 июля 2020

При первом рендеринге (я предполагаю) будет вызываться только хук useFonts, когда вы вернете <AppLoading /> с !fontsLoaded. Остальные ваши хуки находятся в блоке else, что означает, что у вас не будет одинакового количества хуков на каждом рендере.

Проверьте https://reactjs.org/docs/hooks-rules.html для получения дополнительных объяснений, особенно https://reactjs.org/docs/hooks-rules.html#only -крючков-на-верхнем уровне

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...