基本上,我正在用 React Native 构建一个天气应用程序,并使用 WeatherAPI 作为天气 API。基本上我的问题是:假设我搜索了纽约的天气,它给了我 80F,我搜索了达拉斯的天气,但它给了我与纽约天气相同的详细信息。
我知道我的 API 被调用一次,但是如何根据我的文本输入更改多次调用 API? 这是代码:
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);
});
}
现在这个功能可以重复使用了,可以用于所有城市。