如何在 setState 回调中调用 redux 操作?

How can I call a redux action within a setState callback?

我试图在 setState 回调中调用从另一个文件导入的操作,但我收到类型错误,指出它不是函数。

我试过将函数调用移到回调之外,但出现了同样的错误,所以我不确定问题出在哪里。 (虽然我假设某些东西没有正确绑定?)

这是调用动作的代码

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { MDBContainer } from "mdbreact";
import FormBuilder from "./FormBuilder";
import { addForm } from "../actions/formActions";

export class FormBuilderContainer extends Component {
  state = {
    name: "",
    formData: []
  };

  onSubmit = (nameArg, formArg) => {
    this.setState(
      {
        name: nameArg.value,
        formData: formArg
      },
      () => {
        const newForm = {
          name: this.state.name,
          formData: this.state.formData
        };

        // Add form via addForm action
        this.props.addForm(newForm);
      }
    );
  };

  render() {
    return (
      <MDBContainer>
        <FormBuilder formData={this.state.formData} onSubmit={this.onSubmit} />
      </MDBContainer>
    );
  }
}

export default connect(
  null,
  { addForm }
)(FormBuilderContainer);

和 addForm 操作方法

export const addForm = form => (dispatch, getState) => {
  axios
    .post("/api/forms", form, tokenConfig(getState))
    .then(res =>
      dispatch({
        type: ADD_FORM,
        payload: res.data
      })
    )
    .catch(err =>
      dispatch(returnErrors(err.response.data, err.response.status))
    );
  console.log("Saved Form");
};

抛出的错误是:

TypeError: _this.props.addForm is not a function

  30 |                console.log(newForm);
  31 | 
  32 |                // Add form via addForm action
> 33 |                this.props.addForm(newForm);
  34 |            }
  35 |        );
  36 |    };

我认为这里的问题是如何导入 FormBuilderContainer 组件,如您所见,您将其导出为:

export class FormBuilderContainer extends Component

在底部你有:

export default connect(
    null,
    { addForm }
)(FormBuilderContainer);

现在,如果您使用下面的方法导入它,则会出现错误:

import { FormBuilderContainer } from 'path-to-component-file'

你应该像这样导入它:

import FormBuilderContainer  from 'path-to-component-file'

希望对您有所帮助!