Reputation: 7628
I'm making a simple Counter application using React Native and Redux. What I want to is when I click plus button, the counter will +1.
But when I click plus button, the error
Undefined is not an object (evaluating 'this.props.dispatch')
occurs.
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Text, View, StyleSheet, TouchableOpacity} from 'react-native';
import {incrementCounter, decrementCounter} from '../actions';
class Main extends Component{
incrementCounter(){
this.props.dispatch(incrementCounter);
};
decrementCounter(){
this.props.dispatch(decrementCounter);
};
render(){
return(
<View>
<Text>RN + Redux Simple Counter</Text>
<Text>{this.props.count}</Text>
<View>
<TouchableOpacity onPress={this.incrementCounter}>
<Text>+</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.decrementCounter}>
<Text>-</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
count: state.count
}
};
export default connect(
mapStateToProps
)(Main)
How to solve it? . Thanks in advance...
Upvotes: 1
Views: 4791
Reputation: 29814
You need to fully connect
your component to redux. See documentation
import { connect } from 'react-redux'
const ConnectedMain = connect(
mapStateToProps,
mapDispatchToProps
)(Main)
export default ConnectedMain
Dispatch is "indirectly" accessed via mapDispatchToProps
const mapDispatchToProps = (dispatch) => {
return {
onIncrementClick: () => {
dispatch(incrementCounter)
}
}
}
Then call this.props.onIncrementClick()
Upvotes: 1