【发布时间】:2019-03-24 21:28:20
【问题描述】:
我有一个用 ReactJS 构建的应用程序。它的目的是显示食谱,在 food2fork API 中搜索。 我对更新父组件的状态没有任何问题。单击应用程序中的“搜索”按钮后获取数据。 我的问题与将获取的数据作为道具发送给子组件并根据当前搜索正确显示收到的食谱有关。
handleChange 仅用于处理输入。
handleSearch 是我想使用按钮的“onClick”来显示从 API 获取的数据。
获取的食谱应该显示在结果组件中。
希望清楚:)
除了仅将状态作为来自父组件的道具传递并在子组件中使用它之外,我还尝试使用生命周期方法根据收到的道具更新子状态 - 也许我没有正确使用它们...
父组件:
import React, { Component } from 'react';
import Results from './Results';
class Recipes extends Component {
constructor(props){
super(props);
this.state = {
search: '',
recipes: []
}
}
handleChange=e=>{
this.setState({
search: e.target.value
})
}
handleSearch =()=>{
if(this.state.search !== ''){
const url = `https://www.food2fork.com/api/search?key=367d2d744696f9edff53ec5b33a1ce64&q=${this.state.search}`
fetch(url)
.then(data => data.json())
.then(jsonData => {
this.setState((jsonData)=> {return {
recipes: jsonData}
})
})
} else {
console.log('empty')
}
}
render() {
return (
<Wrapper>
<SearchBar
value={this.state.search}
type='search'
onChange={this.handleChange}>
</SearchBar>
<SearchButton onClick={this.handleSearch}>SEARCH</SearchButton>
<Results recipes={this.state.search}/>
</Wrapper>
);
}
}
export default Recipes;
儿童组件“结果”应该接收更新的食谱列表作为道具并显示这些食谱。
import React from 'react';
import Recipe from './Recipe';
class Results extends React.Component {
render(){
return (
<Container>
<RecipesList>
{this.props.recipes.map(item =>
<Recipe
f2fURL={item.f2f_url}
image={item.image_url}
publisher={item.publisher}
publisherURL={item.publisher_url}
recipeID={item.recipe_id}
source={item.source_url}
title={item.title}
/>)}
</RecipesList>
</Container>
);
}
};
【问题讨论】:
-
我认为您可能有错字。看起来您将 this.state.search 作为属性传递给子组件。你应该传入 this.state.recipes :)
标签: reactjs api asynchronous