首页 > 解决方案 > 标识符“reducer”已声明

问题描述

在声明 reducer 的第 7 行,我收到错误消息:“标识符‘reducer’已被声明”。我将尝试删除它并再次将其逐个写出来,但是如果您看到我的问题,请告诉我!

谢谢!

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

const COLOR_INCREMENT = 15;

const reducer = (state, action) => { 
    // state === { red: number, green: number, blue: number }
    // action === { colorToChange: 'red' || 'green' || 'blue' }

    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, runMyReducer] = useReducer(reducer, { red 0, green 0, blue 0 });
    const { red, green, blue } = state;

    return (
        <View>
            <ColorCounter 
                onIncrease={() => runMyReducer({ colorToChange: 'red', amount: COLOR_INCREMENT })} 
                onDecrease={() => runMyReducer({ colorToChange: 'red', amount: -1 * COLOR_INCREMENT })} 
                color="Red" 
            />
            <ColorCounter 
                onIncrease={() => runMyReducer({ colorToChange: 'green', amount: COLOR_INCREMENT })} 
                onDecrease={() => runMyReducer({ colorToChange: 'green', amount: -1 * COLOR_INCREMENT })}  
                color="Green" 
            />
            <ColorCounter 
                onIncrease={() => runMyReducer({ colorToChange: 'blue', amount: COLOR_INCREMENT })} 
                onDecrease={() => runMyReducer({ colorToChange: 'blue', amount: -1 * COLOR_INCREMENT })} 
                color="Blue" 
            />
            <View 
                style={{ 
                    height: 150, 
                    width: 150, 
                    backgroundColor: `rgb(${red}, ${green}, ${blue})`
                }} 
            />
        </View>
    );
};

const styles=StyleSheet.create({});

export default SquareScreen;

标签: javascriptreact-native

解决方案


它在第一行声明:

import React, { reducer } from 'react';


推荐阅读