在使用withRouter的操作创建者中,history.push抛出错误“未处理的拒绝(TypeError):history.push不是函数”

时间:2020-06-25 15:32:02

标签: reactjs react-redux jsx redux-form react-router-dom

在使用redux-form的此表单组件上处理此处的提交时,如果在收到操作创建者的成功承诺后,用户未作为错误{{重定向到/contacts,则会发生错误1}}生成。我/我需要如何将历史记录状态传递给Unhandled Rejection (TypeError): history.push is not a function组件,以便可以正确地重定向用户?我已验证表单已成功提交给API并正确存储在数据库中。该错误仅与ContactForm有关。

ContactForm组件

history.push

操作

import _ from "lodash";
import React, { Component } from "react";
import { reduxForm, Field } from "redux-form";
import { Link } from "react-router-dom";
import ContactField from "./ContactField";
import { connect } from "react-redux";
import formContactFields from "./formContactFields";
import { withRouter } from "react-router-dom";
import * as actions from "../../actions";

class ContactForm extends Component {
    renderFields() {
        return _.map(formContactFields, ({ label, name, value, type }) => {
            return <Field 
                    key={name} 
                    component={ContactField} 
                    label={label} 
                    name={name} 
                    type={type}
                    value={value}
                />
        })
    }

    render() {
        return (
            <div className="form-container">
                <form
                    onSubmit={this.props.handleSubmit(this.props.addContact)}
                >
                    {this.renderFields()}
                    <Link 
                        to="/contacts" 
                        className="btn red darken-1 btn-flat white-text"
                    >
                        <i className="material-icons left">arrow_back</i>
                        <span>Cancel</span>
                    </Link>
                    <button 
                        type="submit"
                        className="btn cyan darken-1 btn-flat white-text right"
                    >
                    <span>Add</span>
                    <i className="material-icons right">add</i>
                </button>
                </form>
            </div>
        );
    }
};

ContactForm = reduxForm({
    form: "newContactForm",
})(ContactForm);

function mapStateToProps(state) {
    return { state };
}

export default connect(mapStateToProps, {actions})(withRouter(ContactForm));

1 个答案:

答案 0 :(得分:1)

history显然将是undefined,因为您无论如何都没有将值传递给操作。它会自动获得values,因为redux-form的{​​{1}}会将它们传递给您提供的任何功能。为了传递额外的值,您需要重新构造将函数传递给handleSubmit的方式。

您将定义传递给handleSubmit的函数。因此,由于您的操作需要访问表单值 handleSubmit,因此您只需声明一个中间函数即可添加额外的值。

history

或者要清理它,可以将其移出内联,如下所示:

onSubmit={this.props.handleSubmit((values) => this.props.addContact(values, this.props.history))}