首页 > 解决方案 > 为什么 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);

标签: javascriptreactjsreduxreact-redux

解决方案


你只需要改变

const mapDispatchToProps = (dispatch) => {
  return {
    saveComment: () => dispatch(saveComment()),
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    saveComment: (comment) => dispatch(saveComment(comment)),
  };
};

推荐阅读