首页 > 解决方案 > 无法理解我的应用程序上的 React-native 错误

问题描述

我一直在学习使用 react-native 的 udemy 教程。我遇到了这个错误,如 iphone 图像所示。我的应用程序的代码如下:当我转到应用程序上显示错误的此文件时,会发生此问题

import React, { useReducer } from 'react' ;
import {View, StyleSheet, Text, FlatList} from 'react-native';
import ColorCounter from '../components/ColorCounter';

const COLOUR_COUNT = 15 ;

const reducer = (state, action)  => {

  switch (action.colorToChange) {
      case 'red':
         return { ...state, red: state.red + action.amount };
      case 'green':
        return { ...state, green: state.green + action.amount };
      case 'blue':
        return { ...state, blue: state.blue + action.amount }; 
      default:
        return state ;
   }
};

const SquareScreen = () => {

    const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0}) ;
    const [red, green, blue] = state ;

    return ( <View>
     <ColorCounter
     onIncrease={() => 
        dispatch ({ colorToChange: 'red', amount: COLOUR_COUNT}) }
     onDecrease={() => 
        dispatch ({ colorToChange: 'red', amount: -1 * COLOUR_COUNT }) } 
     color="Red" 
     />
     <ColorCounter 
     onIncrease={() => 
        dispatch ({ colorToChange: 'blue', amount: COLOUR_COUNT}) } 
     onDecrease={() => 
        dispatch ({ colorToChange: 'blue', amount: -1 * COLOUR_COUNT })}
     color="Blue"/>
     <ColorCounter 
     onIncrease={() => 
        dispatch ({ colorToChange: 'green', amount: COLOUR_COUNT})} 
     onDecrease={() => 
        dispatch ({ colorToChange: 'green', amount: -1 * COLOUR_COUNT })}
     color="Green" />

     <View
       style={{
         height: 150,
         width: 150,
         backgroundColor: `rgb(${red}, ${green}, ${blue})`  
       }}
       />

    </View>
  );
};

const styles = StyleSheet.create({}) ;

export default SquareScreen;

当我转到此代码时出现的错误消息图像如下:

反应错误信息

标签: react-native

解决方案


纠正这个:

const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0}) ;
const {red, green, blue} = state ;

第一行是一个数组解构,第二行是一个对象


推荐阅读