繁体   English   中英

如何在响应工作中执行此操作?

[英]How can I make this action in react work?

当我用console.log(recipe.id)替换“ this.props.fetchInfo(recipe.id)”时,单击div时会记录“ recipe.id”。 但是,该操作永远不会触发。 我的实际动作创建者中还有另一个console.log,如果实际传入ID,它会记录该ID,但是我只是得到一个错误(这是我希望的,但我认为我至少会在错误之前记录该ID。安慰)。 我不确定“食谱”组件的结构是否正确设置,尽管它原样出现。 另外,我不确定是否有更正确的方法来执行我要尝试的操作,即从我的上一个AJAX请求中获取状态的一部分(recipe.id),然后使用它来进行第二个AJAX请求返回我需要的信息。 以下是“配方”组件:

import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-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) {
          console.log(recipe.id);
          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);

好吧,我编码了一些代码,我相信您正在尝试这样做。

 class Recipe extends React.Component { renderFood(foods) { return ( <div> {foods.map(recipe => ( <div key={recipe.id} onClick={() => this.props.fetchInfo(recipe.id)} > <div id="recipe-title">{recipe.title}</div> </div> ) )} </div> ); } render() { const { foods } = this.props; return ( <div> {this.renderFood(foods)} </div> ); } } const foodsList = [ { title: "beans", id: 1 }, { title: "rice", id: 2 }, ]; class Main extends React.Component { state = { received: false, info: null }; fetchInfo(id) { this.setState({ received: true, info: id, }); } render() { const { received, info } = this.state; return ( <div> {received && (<div>{info}</div>)} <Recipe foods={foodsList} fetchInfo={(id) => this.fetchInfo(id)} /> </div> ); }; } ReactDOM.render(<Main />, document.querySelector("#app")); 
 <div id="app"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

您的绑定方式错误。

更换

{food.map(function(recipe) {

{food.map(recipe => {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM