javascript - 如何在组件触发的函数中使用 to action?

标签 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);

最佳答案

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

关于javascript - 如何在组件触发的函数中使用 to action?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53135904/

相关文章:

javascript - jQuery detach() 和remove() 都不适用于附加元素

javascript - 如何在 Edge 中实现基于 AJAX 的长轮询?

javascript - Firebase 单次调用?

javascript - React/Redux 应用程序在 settimeout 内分派(dispatch)操作

javascript - redux-thunk 的唯一好处是什么?

javascript - Laravel Ajax 请求,Auth :login returns false! 但用户在刷新后登录

reactjs - 在 gatsby jsx 中添加 `if` 条件

javascript - 多个状态,相同的 Action 创建者

reactjs - redux 中的选择器是什么?

javascript - 使用 Ember JS 进行多列排序