javascript - 我无法从我的子(类)组件更新我的父组件中的状态
问题描述
- 这是一个食谱应用程序
- 我的搜索(类)组件是子组件
- 我的父组件中的状态需要更新到搜索结果。
- 我的 API 在一个单独的组件中
- 我可以成功 console.log 结果。
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>
提前致谢。
解决方案
里面的数据RecipeList
是从组件传递过来的App
。并且当Search
组件发生变化时,RecipeList
也会发生变化。
因此,当Search
组件发生变化时,我们必须告知App
数据发生了变化。
所以常用的方法就是写 handleSubmit
进去App
传给Search
:
这是一个有效的代码框: https ://codesandbox.io/s/quirky-architecture-ktj3q ?fontsize=14
(我嘲笑了 fetch 部分)
更新:如果您有兴趣,我添加了一个功能组件版本。
https://codesandbox.io/s/shy-worker-8s3zi?fontsize=14
有关功能组件和 Hook 的更多信息:https ://reactjs.org/docs/hooks-intro.html
推荐阅读
- python - 熊猫在指定字符序列后删除部分字符串
- java - gdx-bullet hello world 首次使用
- css - 元素宽度与最宽的子元素一样宽,并排而不占用全宽
- qt - 自定义抓取物品的图像
- java - 为什么有和没有 ExecutorService 的任务花费相同的时间?
- java - 如何运行 Jenkins 并查看测试的可视化运行
- c# - Raise event in C# and catch in C++ MFC
- postgresql - 迭代插入值
- javascript - 无法重现查询参数 html 注入
- elasticsearch - 如何正确使用 SearchAfter API?