Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在REACT中使用用户输入更新API URL调用_Javascript_Reactjs - Fatal编程技术网

Javascript 在REACT中使用用户输入更新API URL调用

Javascript 在REACT中使用用户输入更新API URL调用,javascript,reactjs,Javascript,Reactjs,大家好,我想知道如何用更新的用户输入更新现有的API url调用,并获取新的更新数据。我是个新手,我想不出来。我想获取用户输入并将其添加到API url中,然后获取它并获取更新的数据。但我不知道是否应该在每次收到新道具组件时更新它,或者使用其他方法? 我应该在这里使用react路由器吗(我还没学会)?急需帮助。非常感谢。 这是我的密码 let cityName; export class App extends React.Component{ constructor() { supe

大家好,我想知道如何用更新的用户输入更新现有的API url调用,并获取新的更新数据。我是个新手,我想不出来。我想获取用户输入并将其添加到API url中,然后获取它并获取更新的数据。但我不知道是否应该在每次收到新道具组件时更新它,或者使用其他方法? 我应该在这里使用react路由器吗(我还没学会)?急需帮助。非常感谢。 这是我的密码

   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>);
  }
}
让cityName;
导出类应用程序扩展React.Component{
构造函数(){
超级();
此.state={
城市:'',
临时工:'',
说明:“”,
weatherIconId:“”,
压力:'',
风:'',
湿度:''
}
this.handlechange=this.handlechange.bind(this);
}
手变(e){
this.setState({city:e.target.value});
}
componentDidMount(){
cityName=this.state.city;
常数apikey='ec192677d39c9ad44049bb5c5a477b1b';
取回(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}
&APPiD=${apikey}`)
.then(response=>response.json())
.然后(数据=>this.setState({
描述:数据['weather'][0]['description'],
温度:数学层(数据['main']['temp']-273.15),
风:数据[‘速度’]})
.catch(错误=>console.log('failed to fetch',error));
}
render(){
返回(
你的城市是{this.state.city},温度是{this.state.temp}
以及它的{this.state.description}
);
}
}

只有在组件挂载时才调用API,并且在组件挂载后立即调用API。 如果你想改变城市,你应该在里面处理API调用

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

 }