首页 > 解决方案 > 将动作创建者映射到道具 react redux

问题描述

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

这是反应类代码的样子:

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(null, mapDispatchToProps)(Test)在最后执行

标签: reactjsreduxreact-redux

解决方案


提供完整的 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));

推荐阅读