reactjs - 将动作创建者映射到道具 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)
在最后执行
解决方案
提供完整的 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));
推荐阅读
- c# - C# Windows 窗体 ToolStrip 和 MenuStrip 内存泄漏
- kubernetes - Kubernetes 托管 Auto Scaling 组如何启用指标收集
- git - 如何将源(本地)存储库中的更新(最后几次提交)与使用 git subtree 创建的子目录合并?
- linux - 比较来自多个文件的列值
- python - Python中带有AND条件的LOC搜索字符串
- node.js - 无法读取未定义的属性“forEach”,nodeJS mongoose ejs
- node.js - SAP Business One -> 嵌入式事件的 Rest API
- maven - 无法在项目 SydApp 上执行目标 org.openjfx:javafx-maven-plugin:0.0.6:run (default-cli):错误
- swift - ARKit 对象 2D x, y 位置
- android - 从 Android Kotlin 加密芯片迁移到 Flutter Dart