在声明了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;
答案 0 :(得分:2)
在第一行中声明:
import React, { reducer } from 'react';