首页 > 解决方案 > 如何在组件触发的函数中使用动作?

问题描述

由于我的 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);

标签: javascriptreactjsreduxevent-handlingaction

解决方案


您只是在两个地图中都缺少这个,要么将两者都更改为箭头函数,要么在调用 map 时将其作为第二个参数传递。


推荐阅读