簡體   English   中英

使用REACT中的用戶輸入更新API URL調用

[英]Updating API URL call with user input in REACT

嗨,大家好,我想知道如何使用更新的用戶輸入來更新現有的API URL調用,並獲取新的更新數據。 我是新來的,無法弄清楚。 我想獲取用戶輸入並將其添加到API url中並獲取它並獲取更新的數據。 但是我不知道我是否應該在每次收到新的道具組件或使用其他某種方法時更新它? 我是否應該在這里使用react-router(我還沒學過)? 迫切需要幫助。 謝謝這是我的代碼

   let cityName;
export class App extends React.Component{
constructor() {
  super();
  this.state = {
    city: '',
    temp: '',
    description: '',
    weatherIconId: '',
    pressure: '',
    wind: '',
    humidity: ''
  }
  this.handlechange = this.handlechange.bind(this);
}

handlechange(e) {
  this.setState({city: e.target.value});
}



componentDidMount() {
  cityName = this.state.city;
  const apikey = 'ec192677d39c9ad44049bb5c5a477b1b';
  fetch(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}
    &APPiD=${apikey}`)
    .then(response => response.json())
    .then(data => this.setState({
      description: data['weather'][0]['description'],
      temp: Math.floor(data['main']['temp'] - 273.15),
      wind: data['speed'] }) )
    .catch(error => console.log('failed to fetch', error));
}

  render() {
    return(<div>
<input type='text' onChange={this.handlechange}/>
<h1> Your city is {this.state.city} and temperature is {this.state.temp}
and its {this.state.description}</h1>
      </div>);
  }
}

您僅在componentDidMount時才調用API,並且在掛載組件后就會發生一次。 如果要更改城市,則應在內部處理API調用

handlechange(e) {
  // call here the API and if the call goes well update the state

 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM