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

时间:2019-08-31 14:23:51

标签: javascript reactjs redux callback action

我正在尝试从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不是函数

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

1 个答案:

答案 0 :(得分:0)

我认为这里的问题是如何导入 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'

希望这会有所帮助!