I am trying to learn redux following a tutorial online but when I am almost done I ran into this error this.props.decreaseCounter is not a function. (In '_this.props.decreaseCounter()', '_this.props.decreaseCounter' is undefined)
I am not sure why this is the case. I just changed them to this.props after implementing the mapPropsToDispatch function in counterApp.
App.js
const intialState = {
counterRedux: 0
}
const reducer = (state = intialState, action) => {
switch(action.type){
case 'INCREASE_COUNTER':
return{counter:state.counterRedux 1}
case 'DECREASE_COUNTER':
return{counter:state.counterRedux-1}
}
return state;
}
const store = createStore(reducer);
export default class App extends React.Component {
render() {
return(
<Provider store={store}>
<CounterApp/>
</Provider>
);
}
}
CounterApp.js
class CounterApp extends Component {
render() {
return (
<View style={styles.container}>
<View style={{ flexDirection: 'row', width: 200, justifyContent: 'space-around' }}>
<TouchableOpacity onPress={() => this.props.increaseCounter()}>
<Text style={{ fontSize: 20 }}>Increase</Text>
</TouchableOpacity>
<Text style={{ fontSize: 20 }}>{this.props.counter}</Text>
<TouchableOpacity onPress={() => this.props.decreaseCounter()}>
<Text style={{ fontSize: 20 }}>Decrease</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
function mapStateToProps(state){
return {
counter: state.counterRedux
}
}
function mapDispatchToProps(dispatch){
return {
increaseCounter : () => dispatch({type: 'INCREASE_COUNTER'}),
decreaseCounter : () => dispatch({type: 'DECREASE_COUNTER'}),
}
}
export default connect(mapStateToProps)(CounterApp)
CodePudding user response:
You are not passing mapDispatchToProps to the connect function. Try changing this export from
export default connect(mapStateToProps)(CounterApp)
to
export default connect(mapStateToProps, mapDispatchToProps)(CounterApp)