Undefined is not an object (evaluating 'this.p

2019-07-28 02:57发布

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...

1条回答
Fickle 薄情
2楼-- · 2019-07-28 03:35

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()

查看更多
登录 后发表回答