Reactjs 如何根据状态变量正确更新屏幕
我是新手,我正在学习如何在用户单击按钮后从api获取数据。不知怎么的,我已经把所有的东西都用上了,但我认为我没有正确地使用图书馆 我想到的是:Reactjs 如何根据状态变量正确更新屏幕,reactjs,Reactjs,我是新手,我正在学习如何在用户单击按钮后从api获取数据。不知怎么的,我已经把所有的东西都用上了,但我认为我没有正确地使用图书馆 我想到的是: class App extends React.Component { state = { recipe: null, ingredients: null } processIngredients(data) { const prerequisites = []; const
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>
);
}
}
类应用程序扩展了React.Component{
状态={
配方:空,
成分:空
}
加工成分(数据){
常量先决条件=[];
const randomdemine=data.fines[0];
对于(var i=1;i{
axios.get(“https://www.themealdb.com/api/json/v1/1/random.php那么(
(回应)=>{
这个.processComponents(response.data);
}
)
}
render(){
返回(
饿了吗?
点击下面的按钮,获取一顿饭
点击我!
{this.state.recipe?:}
);
}
}
我在render()中检查state.recipe值的方式调用配方组件,它是正确的吗?或者它看起来像是拼凑在一起的代码吗?如果我做错了,正确的方法是什么?这确实是一个小错误,但在这种情况下,您可以使用内联
&
逻辑运算符,因为对于“false”情况没有任何渲染:
{this.state.recipe&&}
签出以获取更多信息。这确实是一个小问题,但在这种情况下,您可以使用内联
&&
逻辑运算符,因为“false”情况下没有任何可渲染的内容:
{this.state.recipe&&}
查看更多信息