开发者问题收集

React native-‘undefined 不是一个对象’?

2020-07-12
665

好吧,根据这个答案 React native - “this.setState 不是函数”试图为背景颜色设置动画? 我只是想循环淡化 React Native 中视图的背景颜色。

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 and hooks
  //To change state 'color' - setColor('#ff0000');
  const colors = ["#fff", "#ff0000", "#00ff00", "#0000ff", "#0077ff"];
  const [color, setColor] = useState("#fff");
  const [backgroundColor, setBackgroundColor] = useState(new Animated.Value(0));
  const [time, setTime] = useState(0);
  //const t = colors[randNum(0, colors.length)];

  //random num, exclusive
  function randNum(min, max) {
    return Math.floor(min + Math.random() * (max - min));
  }

  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(backgroundColor, {
      toValue: 100,
      duration: 5000
    }).start();
  }, [backgroundColor]);

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

  useEffect(() => {
    const interval = setInterval(() => {
      //setTime(new Date().getMilliseconds());
      setColor("#ff0000");
    }, 36000);
    return () => clearInterval(interval);
  }, []);

有了这个,除了 var bgColor = this.state.color 之外,所有内容都检查出来了,这会产生错误

undefined is not an object evaluating ..

我不明白为什么这是一个问题,因为我将颜色设置为 useState('#fff') 我想在我的样式表中使用 color 作为 backgroundColor .

我该如何正确设置它?

3个回答

如果您的组件是一个函数,那么您不应该使用 this.state. ,而必须直接调用状态名称。

在您的代码中:

var bgColor = color.interpolate({...})

而不是:

var bgColor = this.state.color.interpolate({...})

来自 react DOCS

Reading State

When we want to display the current count in a class, we read this.state.count:

<p>You clicked {this.state.count} times</p>

In a function, we can use count directly:

<p>You clicked {count} times</p>

ESI
2020-07-12

这里有一个例子,不要为动画值创建状态,而是使用 memo 初始化一次并使用计时函数更新它

snack: https://snack.expo.io/GwJtJUJA0

代码:

export default function App() {
  const { value } = React.useMemo(
    () => ({
      value: new Animated.Value(0),
    }),
    []
  );

  React.useEffect(() => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(value, {
          toValue: 1,
          duration: 1000,
        }),
        Animated.timing(value, {
          toValue: 0,
          duration: 1000,
        })
      ])
    ).start();
  }, []);

  const backgroundColor = value.interpolate({
    inputRange: [0, 1],
    outputRange: ['#0dff4d', '#ff390d'],
  });

  return (
    <View style={styles.container}>
      <Animated.View style={{ width: 200, height: 100, backgroundColor }} />
    </View>
  );
}
Ashwith Saldanha
2020-07-12

在函数式组件中,您不能使用 this.state.abc 访问组件的状态属性/变量,而是直接使用状态变量的名称。因此,您应该这样做:

var bgColor = color.interpolate({
      inputRange: [0, 300],
      outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
    });
Hamza Murtaza
2020-07-12