映射动作创建者对道具做出反应

时间:2020-04-10 21:19:39

标签: reactjs redux react-redux

问题陈述:我有一个类组件,我试图在其中单击按钮就调度一个动作。

这是React类代码的样子:

const mapDispatchToProps = dispatch => {
    return {
        // function that I want to call
        handlerFunction(value){
        dispatch(
            // action creator
          addProduct(value)
        )
      }

    }
  }

class Test extends Component {

    state = {value: "Hello World"}
    render() { 
        return ( 
            <div>
                <button onClick={()=>{this.handlerFunction(this.state.value)}}>Push me</button>
            </div>
         );
    }
}

当我单击按钮时,出现以下错误

TypeError: this.handlerFunction is not a function

有人可以帮我解决那件事吗?

编辑:我使用过connect-将其导入文件的开头,并在末尾进行connect(null, mapDispatchToProps)(Test)

1 个答案:

答案 0 :(得分:1)

要提供react-redux的完整示例非常困难,因为您需要添加许多文件才能在项目中包含redux。但是我在这里只提到了一个基本示例,您必须清楚使用Action Reducer来实现redux。

import React, {useEffect, useRef, useState} from 'react';
import {connect, useSelector} from 'react-redux';
import * as ServiceActions from './actions/service.actions';
import withReducer from 'app/store/withReducer';
import reducer from './reducers/service.reducer'
import {bindActionCreators} from "redux";

function TestDispatch(props) {
    const {
        handlerFunction
    } = props;

    return (
        <div>
            <button onClick={() => {
                handlerFunction('Khabir');
            }}>Push me
            </button>
        </div>
    )
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
            handlerFunction: ServiceActions.addProduct()
        },
        dispatch);
}

export default connect(null, mapDispatchToProps)(withReducer('service', reducer)(TestDispatch));