如何在组件触发的函数中使用动作?

时间:2018-11-03 22:04:06

标签: javascript reactjs redux event-handling action

由于在onClick事件中触发了操作,我不断收到错误消息“无法读取未定义的属性'props'”。我希望该动作以商店中的某种状态触发,以向其发出AJAX请求。

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { fetchInfo } from "../actions";

// Here we take in the passed in props from the FoodList component and render
// the dishes for the inputted ingredients

class Recipe extends Component {

  renderFood(food) {
    return (
      <div className="food-container">
        {food.map(function(recipe) {
          return (
            <div
              className="indiv-recipe"
              style={{
                backgroundImage: "url(" + recipe.image + ")"
              }}
              onClick={() => this.props.fetchInfo(recipe.id)}
            >
              <div id="recipe-title"> {recipe.title}</div>
            </div>
          );
        })}
      </div>
    );
  }

  render() {
    return (
      <div>
        <h1>{this.props.foods.map(this.renderFood)}</h1>
      </div>
    );
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchInfo }, dispatch);
}

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

1 个答案:

答案 0 :(得分:0)

在两个地图中都缺少此功能,要么将其更改为箭头函数,要么在调用地图时将其作为第二个参数传递。