由于在我的 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/