Lifecycle 方法是否在 setState 上再次触发?

Do Lifecycle method's trigger again on setState?

我正在创建一个实时天气更新应用程序,它通过输入城市名称和国家/地区代码来提供有关天气的信息。我正在使用 Reactjs 从 https://openweathermap.org API. I am good and have no problem fetching data from it. I am calling a state changing method that changes the initial state of city name and country code by user provided input and my app fetches data from API on clicking the submit button. But every time the input changes, it seems the app fetches data(on seeing console) and after clicking the submit button I get the initial output upon the initial state that I had set. Here is the sample of that API http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22

获取数据

响应可以是 XML 或 JSON。虽然我想要JSON。这是我的代码:

const PATH_BASE='https://api.openweathermap.org/data/2.5/';
const PATH_WEATHER='weather?q=';
const APPID='&appid=71a134a1be2190f78ba5301defa7e44f';
const DEFAULT_CITY='karachi';
const DEFAULT_CC='pk';
const COMMA=',';

 class App extends Component {
   constructor(props){
   super(props);
   this.state={result:null,cityName:DEFAULT_CITY,countryCode:DEFAULT_CC};
   this.setResult=this.setResult.bind(this);
   this.setCity=this.setCity.bind(this);
   this.setCountry=this.setCountry.bind(this);
   this.fetchWeatherUpdates=this.fetchWeatherUpdates.bind(this);
   this.searchSubmit=this.searchSubmit.bind(this);
   }

  fetchWeatherUpdates(cityName,countryCode){
    fetch(`${PATH_BASE}${PATH_WEATHER}${cityName}${COMMA}${countryCode}${APPID}`)
    .then(response=>response.json())
    .then(result=>this.setResult(result))
    .catch(error=>error);  
  }
 componentDidMount(){
    const {cityName,countryCode}=this.state;
    this.fetchWeatherUpdates(cityName,countryCode);
  }
 setResult(result){
   this.setState({result:result});
 }
 setCity(event){
   this.setState({cityName:event.target.value});
 }
 setCountry(event){
   this.setState({countryCode:event.target.value});
 }


 searchSubmit(){
   const {cityName,countryCode}=this.state;
   this.fetchWeatherUpdates(cityName,countryCode);
 }

 render() {
 const {cityName,countryCode}=this.state;
 console.log(this.state.result);
 if(!this.state.result){
   return (<div>Loading...</div>);
 }
 return (
  <div className="App">
  <form onSubmit={this.searchSubmit}>
  <input type="text" value={this.state.cityName} onChange={this.setCity}/>
  <input type="text" value={this.state.countryCode} onChange={this.setCountry}/>
  <button type="submit"> Submit </button>
  </form>
  <h2>
     {this.state.result.weather[0].main}
  </h2>
  </div>
 );
 }
}


export default App;

抱歉,代码很长,但我添加了所有内容,这样可能会帮助您回答并可能会揭示我的愚蠢错误....

componentDidMount 只会在安装组件时 运行 ,所以如果你使用 setState.

就不会再 运行

您没有在提交处理程序中阻止浏览器的默认行为,即重新加载浏览器。通过阻止它,它不会在提交时重新加载。

例子

class App extends Component {
  // ...

  searchSubmit(event) {
    event.preventDefault();

    const { cityName, countryCode } = this.state;
    this.fetchWeatherUpdates(cityName, countryCode);
  }

  // ...
}