我正在运行我的react-native应用程序,但出现错误,例如:找不到变量:dispatch 。我正在使用reducer来管理此应用程序中的不同状态!任何帮助将不胜感激!
import React, {useReducer} from 'react';
import {Button, Text, View} from 'react-native';
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 HomeScreen = () => {
const [state, action] = useReducer(reducer, {red: 0, green: 0, blue: 0});
const {red, green, blue} = state;
return (
<View>
<Button title="Red" onPress=() => {dispatch({colorToChange: 'red', amount: 1})}/>
<Button title="Green" onPress={() => dispatch({colorToChange: 'green', amount: 1})}/>
<Button title="Blue" onPress={() => dispatch({colorToChange: 'blue', amount: 1})}/>
<Text>Red Color:{red}</Text>
<Text>Green Color:{green}</Text>
<Text>Blue Color:{blue}</Text>
</View>
);
};
export default HomeScreen;
答案 0 :(得分:2)
useReducer将派遣作为已命名结构的第二个元素,作为您的命名操作,您应该将use reducer行更改为
const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0});
之后,您将可以使用dispatch ..您现在可以通过调用action()来使用它。但是命名似乎很错误
答案 1 :(得分:1)
第二个变量是useReducer
的分派,因此应为
const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0});