2017-07-25 93 views
1

我正在尝试创建React天气应用程序。在这个应用程序,你可以键入城市的名称,它显示当前的温度。 但caloing API后,我的状态不想更改为其他城市对象(在coponentDidMount方法 - “obje”状态)。React API调用不会更改状态

import React, { Component } from 'react'; 
import Api from './api.js'; 

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     obje: {}, 
     inputValue: 'Paris' 
    } 
    } 
    componentDidMount() { 
    var rootUrl = "http://api.openweathermap.org/data/2.5/weather?q="; 
    var city = this.state.inputValue 
    var key = "&appid=aa32ecd15ac774a079352bfb8586336a"; 
     fetch(rootUrl + city + key) 
     .then(function(response) { 
      return response.json(); 
     }).then(d => { 
      this.setState({obje:d}) 
     }); 

    } 

    handleChange(event) { 
    event.preventDefault(); 

    this.setState({inputValue: this.refs.inputVal.value}); 
    console.log(this.refs.inputVal.value); 
    } 
    render() { 
    return (
     <div> 
     {this.state.obje.name} 
     <form action="" method="" onSubmit={this.handleChange.bind(this)}> 
     <input ref="inputVal" type="text" /> 
     <input type="submit" /> 
    </form> 
     </div> 
    ); 
    } 
} 

export default App; 
+0

控制台中是否有任何错误? –

+0

没有错误发生 – Mac

回答

1

componentDidMount只被调用一次 - 组件挂载时。状态更改不会再次触发该代码,因此XHR请求将不会再次发生。将XHR逻辑拆分为自己的方法并在两个地方调用它,例如:

import React, { Component } from 'react'; 
import Api from './api.js'; 

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     obje: {}, 
     inputValue: 'Paris' 
    } 
    } 
    getWeather() { 
     var rootUrl = "http://api.openweathermap.org/data/2.5/weather?q="; 
     var city = this.state.inputValue; 
     var key = "&appid=aa32ecd15ac774a079352bfb8586336a"; 
     fetch(rootUrl + city + key) 
      .then(function(response) { 
       return response.json(); 
      }).then(d => { 
      this.setState({obje:d}) 
      }); 
    } 
    componentDidMount() { 
    this.getWeather(); 
    } 

    handleChange(event) { 
    event.preventDefault(); 

    this.setState({inputValue: this.refs.inputVal.value},() => { 
     this.getWeather(); 
    }); 
    console.log(this.refs.inputVal.value); 
    } 
    render() { 
    return (
     <div> 
     {this.state.obje.name} 
     <form action="" method="" onSubmit={this.handleChange.bind(this)}> 
     <input ref="inputVal" type="text" /> 
     <input type="submit" /> 
    </form> 
     </div> 
    ); 
    } 
} 

export default App; 
+0

您的想法不解决我的问题。它的效果相同:( – Mac

+0

我没有测试我的代码,但假设你的目标是当用户点击提交时进行API调用 - 这个或者这个的一些变化就是解决方案。你是否检查了控制台并确保新的值正在被记录吗?是否有错误?你是否尝试从'getWeather()'进行日志记录以确保正确调用它? –

+0

我认为问题出在变量“city”beacuse函数getWeather仅触发一次,所以这个变量不能改变。 – Mac

相关问题