javascript - 为什么 mapStateToDispatch 没有发送正确的值
问题描述
我正在尝试从我的组件发送一个操作来更新状态。通常,我将所有动作创建者都放在连接函数中,例如 - connect(mapStateToProps,{actions})(component)。
但是在看了技术图之后,我想为我的连接 HOC 制作一个 mapDispatchToProps。
现在我面临的问题是,以我通常的方式,状态正在使用正确的有效负载进行更新。但是每当我尝试在我的连接 HOC 中插入 mapDispatchToProps 时,动作就会触发,但有效负载不会被发送。
我附上代码片段以便于理解
//actions ------------------
import { SAVE_COMMENT } from "actions/types";
export function saveComment(comment) {
return {
type: SAVE_COMMENT,
payload: comment,
};
}
//reducer ------------------
import { SAVE_COMMENT } from "actions/types";
export default function (state = [], action) {
switch (action.type) {
case SAVE_COMMENT:
return [...state, action.payload];
default:
return state;
}
}
//component ------------------
import React, { Component } from "react";
import { connect } from "react-redux";
import { saveComment } from "actions/index";
class CommentBox extends Component {
state = {
comment: "",
};
handleChange = (e) => {
this.setState({ comment: e.target.value });
};
handleSubmit = (e) => {
e.preventDefault();
//call an action creator and save the comment
this.props.saveComment(this.state.comment);
this.setState({ comment: "" }); //to empty-out the textarea
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<h4>Add a Comment</h4>
<textarea value={this.state.comment} onChange={this.handleChange} />
<div>
<button>Submit Comment</button>
</div>
</form>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
saveComment: () => dispatch(saveComment()),
};
};
export default connect(null, mapDispatchToProps)(CommentBox);
解决方案
你只需要改变
const mapDispatchToProps = (dispatch) => {
return {
saveComment: () => dispatch(saveComment()),
};
};
到
const mapDispatchToProps = (dispatch) => {
return {
saveComment: (comment) => dispatch(saveComment(comment)),
};
};
推荐阅读
- azure-devops - 是否可以在 YAML 文件中定义分支策略?
- python - 如何在函数外使用函数中的变量
- graphviz - 如何在 Graphviz 中垂直对齐子图簇?
- r - 根据另一列的值平均一列的特定行
- .net - 如何使用配置转换删除环境变量
- javascript - 如何理解这个高阶函数闭包发生了什么
- java - 如何从 Hibernate 元数据中获取特定类/实体的所有子类的列表?
- react-native - 加载组件时满足条件时如何在标题中添加按钮?
- java - 自动扩展 TextField 以适应文本
- calculator - 使用基于矩阵的任意数库 (HP Prime) 的乘法