class App extends Component {
state = {
recipes: []
};
componentDidMount() {
recipesData()
.then(data => this.setState({ recipes: data.recipes }))
}
render() {
return (
<div className="App">
<Search/>
<RecipeList data={this.state.recipes} />
</div>
class Search extends Component {
state = {
search: ""
};
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
handleSubmit = e => {
e.preventDefault();
const key = "KEY";
const url = `https://www.food2fork.com/api/search?key=${key}&q=${
this.state.search
}&page=2`;
fetch(url)
.then(res => res.json())
.then(res => {console.log(res)})
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="search"
value={this.state.search}
onChange={this.handleChange}
/>
<button type="submit">Search</button>
</form>
</div>
谢谢。
答案 0 :(得分:0)
RecipeList
中的数据是从App
组件传递的。并且当Search
组件更改时,RecipeList
也将更改。
因此,当Search
组件更改时,我们必须告诉App
数据已更改。
因此,常见的方法是将handleSubmit
写到App
并将其传递给Search
:
这是一个有效的代码框: https://codesandbox.io/s/quirky-architecture-ktj3q?fontsize=14
(我嘲笑提取部分)
更新:如果您感兴趣,我添加了此功能的组件版本。
https://codesandbox.io/s/shy-worker-8s3zi?fontsize=14
有关功能组件和挂钩的更多信息:https://reactjs.org/docs/hooks-intro.html
答案 1 :(得分:0)
只需将更新方法传递给子组件,然后从子组件调用该方法,然后将响应作为参数传递给方法,就可以更新父组件状态< / p>
class App extends Component {
state = {
recipes: []
};
componentDidMount() {
}
updateRecipe = (data) =>{
this.setState({recipes:data.recipes})
}
render() {
return (
<div className="App">
<Search update={(data)=>this.updateRecipe(data)}/>
<RecipeList data={this.state.recipes} />
</div>
)}
}
class Search extends Component {
state = {
search: ""
};
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
handleSubmit = e => {
e.preventDefault();
const key = "KEY";
const url = `https://www.food2fork.com/api/search?key=${key}&q=${
this.state.search
}&page=2`;
fetch(url)
.then(res => res.json())
.then(res => {this.props.update(res)})
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="search"
value={this.state.search}
onChange={this.handleChange}
/>
<button type="submit">Search</button>
</form>
</div>
)}
}