我正在使用React Native和Redux创建一个简单的Counter应用程序。我想要的是当我点击加号按钮时,计数器将+1。
但是当我点击加号按钮时,错误
未定义不是对象(评估' this.props.dispatch')
发生。
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)
如何解决? 。提前谢谢......
答案 0 :(得分:1)
您需要完全connect
您的组件才能减少。见documentation
import { connect } from 'react-redux'
const ConnectedMain = connect(
mapStateToProps,
mapDispatchToProps
)(Main)
export default ConnectedMain
派遣是间接的&#34;通过mapDispatchToProps
const mapDispatchToProps = (dispatch) => {
return {
onIncrementClick: () => {
dispatch(incrementCounter)
}
}
}
然后拨打this.props.onIncrementClick()