如何解决以响应方式每个文本输入获取多次
我很乐意在响应本机中构建一个Weather应用程序,并使用weatherAPI作为weather API。这么大声地说,我的问题是:假设我搜索了纽约的天气,它给了我80F,然后搜索了达拉斯的天气,但是它给了我与纽约天气相同的详细信息。
我知道我的API被调用一次,但是如何根据我的textinput更改多次进行APIcall? 这是代码:
constructor(props) {
super(props);
this.state = {
weatherText: "Enter",isLoading: true,locationData: [],currentData: []
};
}
componentDidMount(){
this.apiCALL()
}
apiCALL(){
return fetch(
`http://api.weatherapi.com/v1/current.json?key=???&q=${this.state.weatherText}`//I took out the key on purpose.
)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,locationData: responseJson.location,currentData: responseJson.current,});
})
.catch((error) => {
console.log(error);
});
}
注意:我故意拿出了API的密钥。
那么我该如何做到这一点。就像我之前说过的,当Textinput更改时如何调用API?
我是否应该使用ComponentDidMount
或是否有其他内置函数/方法来实现此目的?。
解决方法
当文本输入更改时或在文本输入旁边的提交按钮上调用它,而不是在componentDidMount
上调用api。
假设您有TextInput
,请使用
<TextInput placeholder="eg. New York" onChange={(val)=>this.apiCALL(val)}/>
并将apiCALL
修改为
apiCALL(city){
return fetch(
`http://api.weatherapi.com/v1/current.json?key=???&q=${city}`//I took out the key on purpose.
)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,locationData: responseJson.location,currentData: responseJson.current,});
})
.catch((error) => {
console.log(error);
});
}
现在此功能可以重复使用,并且可以在所有城市使用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。