【问题标题】:Undefined is not an object (evaluating 'this.props.dispatch') in React NativeUndefined 不是 React Native 中的对象(评估“this.props.dispatch”)
【发布时间】:2017-02-27 18:02:51
【问题描述】:

我正在使用 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)

如何解决? .提前谢谢...

【问题讨论】:

    标签: reactjs react-native redux


    【解决方案1】:

    你需要完全connect你的组件来redux。见documentation

    import { connect } from 'react-redux'
    
    const ConnectedMain = connect(
      mapStateToProps,
      mapDispatchToProps
    )(Main)
    
    export default ConnectedMain
    

    Dispatch 通过mapDispatchToProps“间接”访问

    const mapDispatchToProps = (dispatch) => {
      return {
        onIncrementClick: () => {
          dispatch(incrementCounter)
        }
      }
    }
    

    然后拨打this.props.onIncrementClick()

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 2022-01-23
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 2021-12-23
      相关资源
      最近更新 更多