我正在将异步函数从App传递到Header到Form。即使使用arrow函数,我似乎也无法使用Submit事件处理程序调用该函数。
我尝试了胖箭头功能。唯一的工作方式是将功能向下移动到可以正常工作的Form,但并不理想,因为我需要将数据存储在App状态下。当我console.log(result)
不确定时
class Form extends Component {
constructor(props){
super(props);
this.state = {value: ''};
}
handleChange=(e)=> {
this.setState({value: e.target.value});
}
handleSubmit= (e)=>{
e.preventDefault();
const value = this.state.value;
this.props.getResult(value)
}
render(){
return (
<form className="search"onSubmit={this.handleSubmit}>
<input type="text" className="search__field" placeholder="Search over 1,000,000 recipes..." value={this.state.value} onChange={this.handleChange}/>
<button className="btn search__btn"></button>
</form>
);
}
}
应用程序组件
class App extends Component {
constructor(props) {
super(props);
this.state = {
search:[],
}
}
getResult = async (query) =>{
try {
const key = 'key';
const res = await axios(`https://www.food2fork.com/api/search?key=${key}&q=${query}`);
const result = res.data.recipes;
console.log(result)
// if(result) this.setState({search: result});
}
catch (err) {
alert(err);
}
}
render() {
return (
<div className="App">
<div className="container">
<Header getResult={this.getResult}/>
</div>
</div>
);
}
}
标题
class Header extends Component {
constructor(props) {
super(props);
this.getResult = this.props.getResult;
}
render(){
return (
<div className="header">
<Logo />
<Form getResult={this.getResult}/>
<Like />
</div>
)
}
}