找不到 variable:dispatch
Can't find variable:dispatch
我是 运行 我的 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;
第二个变量是来自useReducer
的调度,所以它应该是
const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0});
useReducer returns dispatch 作为解构数组的第二个元素在你的例子中它被命名为 action,你应该将你的 use reducer 行更改为
const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0});
在此之后您将能够使用 dispatch.. 您现在可以通过调用 action() 来使用它.. 但是命名似乎很不对
我是 运行 我的 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;
第二个变量是来自useReducer
的调度,所以它应该是
const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0});
useReducer returns dispatch 作为解构数组的第二个元素在你的例子中它被命名为 action,你应该将你的 use reducer 行更改为
const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0});
在此之后您将能够使用 dispatch.. 您现在可以通过调用 action() 来使用它.. 但是命名似乎很不对