如何解决我想要 React js 中 ComponentDidMount 和 ComponentDidUpdate 的组合功能
我正在使用 axios 获取 API 数据,并且该 API 具有查询参数(例如:searchQuery,它在状态中定义)。我已经在 state 中声明了它的初始值,并在 componentDidUpdate 中进行了 axios 调用。 现在我希望我的用户以提交时将更改“seachQuery”状态的表单输入数据。 问题来了,我想根据用户的输入使用提供的值和未来的结果显示初始结果,但它没有发生。最初的结果没有显示出来,因为只有在更新后才会调用 componentDidUpdate。如果我在 componentDidMount 中进行 axios 调用,则不会出现根据用户输入的结果。我只想使用基于类的组件来做这件事。
constructor(props) {
super(props)
this.state = {
searchResult: [],formInput: "",searchQuery: "chicken",}
}
componentDidUpdate(){
axios.get(`https://api.edamam.com/search?
q=${this.state.searchQuery}&app_id=${this.state.APP_ID}&app_key=${this.state.APP_KEY}`)
.then(res=>
this.setState(prevState =>({searchResult: prevState.searchResult.concat(res.data.hits)}))
)
}
onChangeHandler = (e) => {
this.setState({
formInput: e.target.value
})
console.log(e.target.value)
}
onSubmitHandler = (e) => {
e.preventDefault()
this.setState({
searchQuery: this.state.formInput
})
// console.log(this.state.searchQuery)
// setformInput("")
}
render() {
return (
<div className="App">
<form className="search-form" onSubmit={this.onSubmitHandler}>
<input className="search-bar" type="text" onChange={this.onChangeHandler} />
<button className="search-button" type="submit">SEARCH</button>
</form>
<div className="recipes">
{this.state.searchResult.map(singleRecipe =>
<Recipe key={singleRecipe.recipe.label} title={singleRecipe.recipe.label} calories={singleRecipe.recipe.calories} image={singleRecipe.recipe.image} ingredients={singleRecipe.recipe.ingredients}/>
)}
</div>
</div>
);
}
}
export default App```
解决方法
我认为您可以在 componentDidMount 中设置状态(例如 searchQuery)。
componentDidMount() {
this.setState({searchQuery: 'checken'});
}
,
为什么在提交时将 formInput 设置为用户输入并将 searchQuery 设置为 formInput?只需将 searchQuery 设置为用户输入 onChange。
onChangeHandler = (e) => {
this.setState({
searchQuery: e.target.value
});
console.log(e.target.value);
}
并在函数中获取数据,在 componentDidMount 和 onSubmit 上使用它。
getData = () => {
axios.get(`https://api.edamam.com/search? q=${this.state.searchQuery}&app_id=${this.state.APP_ID}&app_key=${this.state.APP_KEY}`)
.then(res =>
this.setState(prevState => ({ searchResult: prevState.searchResult.concat(res.data.hits) }))
);
}
componentDidMount() {
this.getData();
}
onSubmitHandler = (e) => {
e.preventDefault();
this.getData();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。