在本机反应中每个文本输入获取多次

Fetch Multiple times per textinput in reactnative

所以基本上我正在构建一个天气应用程序以响应本机并使用天气 API 来表示天气 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 还是有一些其他内置的 function/method 来实现这个?

不要在 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);
    });
}

现在这个函数是可重复使用的,可以用于所有的城市。