javascript - 如何在组件触发的函数中使用动作?
问题描述
由于我的 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 时将其作为第二个参数传递。
推荐阅读
- javascript - 如何使用图表 Js 查找每年的项目总和
- python - 字符串之间的空间
- python - Python烧瓶无法在中间件中获取标头值
- process - PC寄存器可以指向与文本段不同的内存区域吗?
- c++ - c++ std::ifstream 构造函数:为什么构造函数使用单个参数解析以及为什么它不能用 c++ 样式实例化对象
- javascript - Google Maps API 获取位置地址和域信息
- onclick - 单击时缩放到标记位置 -OpenLayers
- javascript - JavaScript 匿名函数回调和 redux-saga .next()
- android - 如何在 Android 中直接以画中画模式启动 Activity
- javascript - 如何在 onclick 函数中发送两个参数 id 和 name?