大家好我想知道如何使用更新的用户输入更新我现有的API网址调用并获取新的更新数据。我是新手,反应无法弄明白。我想获取用户输入并将其添加到API网址中并获取它并获取更新的数据。但我不知道每次新的道具组件收到或使用其他一种方法时我是否应该更新它? 我应该在这里使用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>);
}
}
答案 0 :(得分:0)
您只在componentDidMount时调用API,并且一旦安装了组件就会发生一次。 如果您想要更改城市,您应该在
中处理API调用handlechange(e) {
// call here the API and if the call goes well update the state
}