首页 > 解决方案 > 调度不是一个函数反应

问题描述

我正在使用 react 和 redux 开发应用程序。我使用 api。

申请流程:

第一个组件是您输入信息(姓名、卡路里、饮食类型)的表格。

    class FormPage extends Component {
      constructor(props) {
        super(props);

        this.handleFormSubmit = this.handleFormSubmit.bind(this);
        this.goToListOfMealPage = this.goToListOfMealPage.bind(this);
      }

      handleFormSubmit(data) {
        const name = data.name;
        const calories = data.caloreis;
        const diet = data.diet;
        const health = data.health;

        console.log(name)
        return loadData( name, calories, diet, health)()
          .then(({ error }) => {
            if (!error) {
              setTimeout(this.goToListOfMealPage, 1500);
            }

            return error;
          }
        );
      }

      goToListOfMealPage() {
        const { history } = this.props;
        history.push('/ListMeal');
      }

      render() {
        return (
          <Form onSubmit={this.handleFormSubmit}/>
        );
      }
    }

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

FormPage = connect(mapDispatchToProps)(FormPage)
export default FormPage;

handleFromSubmit功能是将表单数据发送到api链接(https://api.edamam.com/search?q= ${name}n&app_id=${key.id}&app_key=${key.key}&calories=${calories }&health=${health}&diet=${diet})。

填写表格并单击发送按钮后,我想在新的子页面上有一份膳食(食谱)列表。

loadData在哪里

const fetchDataStart = () => ({
  type: actionTypes.FETCH_DATA_START,
});

const fetchDataSucces = (data) => ({
  type: actionTypes.FETCH_DATA_SUCCESS,
  data,
});

const fetchDataFail = () => ({
  type: actionTypes.FETCH_DATA_FAIL,
});

const loadData = (name, calories, diet, health) => (dispatch) => {
  dispatch(fetchDataStart());
  return axios.get(`https://api.edamam.com/search?q=${name}n&app_id=${key.id}&app_key=${key.key}&calories=${calories}&health=${health}&diet=${diet}`)
    .then(({ data }) => console.log(data) || dispatch(fetchDataSucces(data)))
    .catch((err) => dispatch(fetchDataFail(err.response.data)));
};

发送表格后,我收到一个错误TypeError: dispatch is not a function

在此处输入图像描述

我找不到这个错误的原因

标签: reactjsreduxreact-redux

解决方案


您的代码存在一些问题:

  • 如果您已将调度映射到道具,则可以通过执行来调用该操作this.props.loadData(params)
  • 您不应该通过这样做来调用该操作,loadData()()因为分派的操作不会返回一个函数(尽管原始操作返回一个函数,但不要让它欺骗您)。

因此,要使用loadData()动作,您需要将其映射到道具,如下所示:

const mapDispatchToProps = dispatch => ({
  loadData: (name, calories, diet, health) => dispatch(loadData(name, calories, diet, health)),
});

然后像这样使用它:

componentDidMount() {
  this.props.loadData(name, calories, diet, health)
    .then(() => console.log('Success'))
    .catch(err => throw new Error("Error", err.stack))
}

编辑:根据您新编辑的问题,redux 中的 connect 函数分别接受mapStateToPropsmapDispatchToProps,因此在您的代码中应该是:

export default connect(null, mapDispatchToProps)(Component)

推荐阅读