调度不是函数反应

时间:2019-03-19 10:03:27

标签: reactjs redux react-redux

我正在使用React和Redux开发应用程序。我使用api。

申请流程:

  • 填写表格,
  • 点击发送按钮,
  • 将数据从表单发送到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

enter image description here

我找不到此错误的原因

2 个答案:

答案 0 :(得分:3)

您的代码存在一些问题:

  • 如果您已将调度映射到prop,则可以通过执行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)

答案 1 :(得分:1)

  1. 不需要您的构造函数-您可以通过这种方式自动绑定函数。

  2. 如果组件中没有mapStateToProps,请将其保持为null。

编辑代码:

import React from 'react';
// Your imports

class FormPage extends Component {
  handleFormSubmit = (data) => {
    const { name, caloreis, diet, health } = data;
    this.props.loadData(name, caloreis, diet, health);
  }

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

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

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

export default connect(null, mapDispatchToProps)(FormPage);

有关重定向的建议:

  1. 您必须在redux状态下保持成功和提交错误,如果成功-您可以重定向到goToListOfMealPage-您可以在componentWillReceiveProps中执行此操作。 我们应该做类似下面的代码:
class FormPage extends Component {
  componentWillReceiveProps(nextProps) {
    if (this.props.formSubmitSuccess !== nextProps.formSubmitSuccess && nextProps.formSubmitSuccess) {
      this.goToListOfMealPage()
    }
  }
  //... rest of the code.
}

// Your map state to props:
const mapStateToProps = state => ({
  formSubmitSuccess: state.reducerIdentifier.formSubmitSuccess,
  formSubmitFailure: state.reducerIdentifier.formSubmitFailure
});