Javascript 如何使用componentDidMount和Async以组件状态保存API调用的输入项?
我无法在每个字母输入时将“input”字段保存到组件的状态中,以进行API调用并使用componentDidMount()Javascript 如何使用componentDidMount和Async以组件状态保存API调用的输入项?,javascript,reactjs,asynchronous,input,Javascript,Reactjs,Asynchronous,Input,我无法在每个字母输入时将“input”字段保存到组件的状态中,以进行API调用并使用componentDidMount() 如果我在组件的状态中手动输入一个单词,我可以通过API检索信息,但我无法通过输入更新状态“值” 我错过什么了吗? 也许是我刚刚开始发现的异步部分 import React from 'react' import { Component } from "react"; class ApiMaze extends Component { const
如果我在组件的状态中手动输入一个单词,我可以通过API检索信息,但我无法通过输入更新状态“值”
我错过什么了吗? 也许是我刚刚开始发现的异步部分
import React from 'react'
import { Component } from "react";
class ApiMaze extends Component {
constructor(props) {
super(props);
this.state = {
informations: [], //La liste contient tout les éléments récupérés dans le fetch de l'API
value: ""
};
}
// Fonction fléchée
handleInput = (event) => this.setState({ value: event.target.value });
// Fonction normale
handleSubmit(event) {
event.preventDefault();
}
// Life Cycle: Se produit après que le composant soit chargée
async componentDidMount() {
const url = "http://api.tvmaze.com/search/shows?q=" + this.state.value
const response = await fetch(url);
const data = await response.json();
this.setState({informations: data})
console.log(this.state.informations);
}
// Rendu final
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<div>
<input type="text" value={this.state.value} required onChange={this.handleInput} placeholder="Name of the serie" />
</div>
</form>
<div >
{this.state.informations.map(serie =>(
<div className="apiResult" key={serie.show.id}>
{serie.show.name}
<br></br>
{serie.show.summary}
</div>
))}
</div>
</div>
)
}
}
export default ApiMaze;
从“React”导入React
从“react”导入{Component};
类扩展组件{
建造师(道具){
超级(道具);
此.state={
信息:[],//La liste contient tout leséléments récupérés dans le fetch de l'API
值:“”
};
}
//弗雷切赫基金会
handleInput=(event)=>this.setState({value:event.target.value});
//正态函数
handleSubmit(事件){
event.preventDefault();
}
//生命周期:生产过程中所需的成分
异步组件didmount(){
常量url=”http://api.tvmaze.com/search/shows?q=“+this.state.value
const response=等待获取(url);
const data=wait response.json();
this.setState({informations:data})
console.log(this.state.informations);
}
//人都决赛
render(){
返回(
{this.state.informations.map(serie=>(
{serie.show.name}
{serie.show.summary}
))}
)
}
}
导出默认值;
问题是ComponentDidMount并不是每次都调用。您可以改为使用componentDidUpdate。有关生命周期的更多信息,请查看此处。您是如何发现值的状态未更新的?
?每次我键入时,都不会发生任何事情。当我提交且未加载任何内容时,该字段再次变为空。我在handleInput中添加了一个console.log,事实上输入似乎被捕获了。所以我不明白为什么在组件的状态中没有考虑到这一点。每次键入时都不应该发生任何事情。需要做的就是更改输入中的值。这是您的手输入doesHello,谢谢您的反馈!您的方法可以工作,但不能完全响应我想要做的事情,即更新输入中输入的每个字母的渲染。Praneth给出了答案:我只需要将componentDidMount更改为ComponentDidUpdate。无论如何,谢谢你的帮助,我真的很感激:)太好了,它现在工作得很好!谢谢你的帮助@克里斯,如果我能解决你的问题,你能把我的回答标记为接受吗:-)