javascript - 我无法在我的 React + Redux 应用程序中使用 mapDispatchToProps
问题描述
在我的 React + Redux 应用程序中,我正在尝试使用mapDispatchToProps实用程序,但是每当我将其放入其中时connect(mapStateToProps, mapDispatchToProps)
,它都会给我一个错误提示Uncaught TypeError: dispatch is not a function at new ReduxApp (ReduxApp.js:42)
这可能是什么问题?PS:下面是文件
ReduxApp.js
import React from 'react';
import { Router, Route } from 'react-router-dom';
import { connect } from 'react-redux';
import { history } from './_helpers';
import { alertActions } from './_actions'
class ReduxApp extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
const { dispatch } = this.props;
dispatch(alertActions.success("hello world"));
}
handleChange(){
this.props.dispatch(alertActions.clear());
}
render(){
const { alert } = this.props;
return(
<div>
<h1>{alert.message}</h1>
<button onClick={this.handleChange}>clear</button> {/* this is working since this function is declared outside the mapDispatchToProps. */}
<button onClick={this.props.handleClick}>clear</button>
</div>
);
}
}
const mapStateToProps = (state) => ({
alert : state.alert
});
const mapDispatchToProps = (dispatch) => ({
handleClick: () => dispatch(alertActions.clear())
});
const connectedApp = connect(mapStateToProps, mapDispatchToProps)(ReduxApp); // when I add mapDispatchToProps in the connect(), I get thhe issue.
export { connectedApp as ReduxApp }
解决方案
您首先需要通过dispatch
,因为它在使用时不可用mapDispatchToProps
(请参阅@gaeron Redux 的创建者的这个答案:https ://github.com/reduxjs/react-redux/issues/255 )
const mapDispatchToProps = dispatch => ({
handleClick: () => alertActions.clear(dispatch),
dispatch,
});
更新您的 actionCreator 以调度操作,因为dispatch
' 的参考可用:
alert.clear = dispatch => {
// your logic
dispatch(ALERT_CLEAR_ACTION) // or whatever you named your action
}
在你的组件中:
handleChange = () => this.props.handleClick();
推荐阅读
- reactjs - SyntaxError:无法在模块 React 路由器之外使用 import 语句
- java - Java 上的 LRU 项目
- php - Laravel 伪造者工厂
- c++ - G++ 编译器找不到 iostream 所需的标头
- json - 在同一文件夹级别的 JSON 文件上导入错误 - 打字稿
- javascript - 在 ASP.Net MVC 5 中将 javascript 数组从视图传递到控制器
- python - 视图中的 Django 模型数据作为变量
- oracle - OracleDB:如何知道一个表行事务的 CSN?
- javascript - 根据选择的值在数据库中获取不同的值
- c# - BizTalk - 使用具有多个命名空间的 xpath 提取元素值