Как остановить многократное срабатывание события в функции onClick с помощью React? - PullRequest
0 голосов
/ 03 августа 2020

Я новичок в React, и у меня есть кнопка onClick, которая должна срабатывать для одного элемента. Вместо этого все элементы с этой кнопкой срабатывают сразу, даже если я нажимаю на нее один раз. Как я могу заставить эту кнопку срабатывать для конкретного элемента, к которому она прикреплена. Я пробовал читать документы, но мне кажется, что они не дают мне ответа на мой вопрос. Может ли кто-нибудь указать мне правильное направление.

Вот мой код:

class App extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      userInput: '',
      getRecipe: [],
      ingredients: "none",

    }
  }

  handleChange = (e) => {
    this.setState({
      userInput: e.target.value
    })
  }

  handleSubmit = (e) => {
    e.preventDefault()

    const getData = () => {
      fetch(`https://api.edamam.com/search?q=${this.state.userInput}&app_id=${APP_ID}&app_key=${APP_KEY}&from=0&to=18`)
        .then(res => {
          return res.json()
        }).then(data => {
          this.setState({
            getRecipe: data.hits
          })
        })
    }
    getData()
  }
 // here is where the event fires 
  getIngredients = (e) => {
    e.preventDefault()
    if (this.state.ingredients === 'none') {
      this.setState({
        ingredients: "block"
      })
    } else {
      this.setState({
        ingredients: "none"
      })
    }

  }


  render() {

    return (
      <div className="recipes">
        <Nav changed={this.handleChange} submit={this.handleSubmit} />
        <Content
          userInput={this.state.userInput}
          recipe={this.state.getRecipe}
          getIngredients={this.getIngredients}
          ingredients={this.state.ingredients} />
      </div>
    )
  }
}

const Content = ({ userInput, recipe, getIngredients, ingredients }) => {

    return (
        <div>
            <h2 className="userinputtitle"> {userInput} </h2>
            <div className="containrecipes">
                {recipe.map(rec => {

                    return (
                        <div key={rec.recipe.label} className="getrecipes">
                            <h1 className="recipetitle" >{rec.recipe.label.toUpperCase()}</h1>
                            <img src={rec.recipe.image}></img>
                            <h4 className="health"> Health Labels: {rec.recipe.healthLabels.join(', ')}</h4>
                            <h4 className="cautions"> Cautions: {rec.recipe.cautions.join(', ')}</h4>
                            <h4 > Diet Label: {rec.recipe.dietLabels}</h4>
                            <h4 > Calories: {Math.floor(rec.recipe.calories)}</h4>
                            <div>
                                <h4>{rec.recipe.digest[0].label + ":" + " " + Math.floor(rec.recipe.digest[0].total) + "g"}</h4>
                                <h4>{rec.recipe.digest[1].label + ":" + " " + Math.floor(rec.recipe.digest[1].total) + "g"}</h4>
                                <h4>{rec.recipe.digest[2].label + ":" + " " + Math.floor(rec.recipe.digest[2].total) + "g"}</h4>
                            </div>
                       // this is where the event fires and all the ingredients for all the divs show up when i only want the one i clicked on to show up 
                            <button onClick={getIngredients} className="getingredients">Ingredients</button>
                            {rec.recipe.ingredients.map(i => {
                                return (
                                    <div style={{ display: ingredients }} className="containingredients">
                                        < ul className="ingredients">
                                            <li key={rec.recipe.ingredients} className="ingredient">{i.text}</li>
                                        </ul>
                                    </div>
                                )

                            })}
                        </div>

                    )
                })}
            </div>
        </div>

    )
}

1 Ответ

0 голосов
/ 04 августа 2020

Вам нужно указать с помощью некоторого идентификатора, какие ингредиенты рецепта вы хотите получить. отправьте этот идентификатор в качестве параметра в методе getIngredients () и проверьте его, и только затем верните данные.

Или вы можете сделать что-то вроде этого,

condition? getIngredients (): e.preventDefault ()}> Ингредиенты

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...