如何根据状态变量正确更新屏幕

时间:2021-03-28 06:29:40

标签: reactjs

我刚开始反应,我正在学习如何在用户单击按钮后从 api 获取数据。不知何故,我已经让一切正常工作,但我认为我没有正确使用图书馆。

我想出了什么:

class App extends React.Component {

  state = {
    recipe: null,
        ingredients: null
    }

    processIngredients(data) {
        const prerequisites = [];
        const randomMeal = data.meals[0];

        for(var i = 1; i <= 20; i++){
            if(randomMeal['strIngredient' + i]){
                prerequisites.push({
                    name: randomMeal['strIngredient' + i],
                    amount: randomMeal['strMeasure' + i]
                })
            } 
        }
        this.setState({
      recipe: data,
            ingredients: prerequisites,
        })
        console.log(prerequisites[0].name)
    }

  getRecipes = () => {
    axios.get("https://www.themealdb.com/api/json/v1/1/random.php").then(
      (response) => {
        this.processIngredients(response.data);
      }
    )
  }

  render() {
    return (
      <div className="App">
        <h1>Feeling hungry?</h1>
       <h2>Get a meal by clicking below</h2>
       <button className="button" onClick={this.getRecipes}>Click me!</button>
       {this.state.recipe ? <Recipe food={this.state.recipe} 
          materials={this.state.ingredients} /> : <div/>}
      </div>
    );
  }
}

我在 render() 中检查 state.recipe 的值并调用 Recipe 组件的方式是否正确?或者它看起来像黑客攻击的代码?如果我做错了,正确的做法是什么?

1 个答案:

答案 0 :(得分:2)

这确实是一个小问题,但在这种情况下,您可以使用内联 && 逻辑运算符,因为对于“false”情况没有什么可呈现的:

{this.state.recipe && <Recipe food={this.state.recipe} materials={this.state.ingredients} />}

查看 https://reactjs.org/docs/conditional-rendering.html 了解更多信息。