TypeError:无法读取null的属性“温度”

时间:2019-03-25 10:14:05

标签: reactjs api data-binding

我是React的新手-我得到了TypeError: Cannot read property 'temperature' of null,它不允许我将温度变量绑定到return()中的组件。在绑定数据之前,我可以在控制台中看到它们。 代码:     类应用扩展了React.Component {     状态:{     温度:未定义     城市:未定义,     国家:未定义,     湿度:不确定     说明:未定义,     错误:未定义     }     getWeather =异步(e)=> {     e.preventDefault();

const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
const api_call = await 
fetch(`http://api.openweathermap.org/data/2.5/weather? 
q=${city},${country}&appid=${API_KEY}&units=metric`);
const data = await api_call.json();
console.log(data);
 this.setState({
   temperature: data.main.temp,
    city: data.name,
    country: data.sys.country,
    humidity: data.main.humidity,
    description: data.weather[0].description,
    error: ""
 });
}


render(){
return (
  <div>
    <h2>Check Weather Component</h2>
    <Titles />
    <Form getWeather={this.getWeather}/>
    <Weather
      temperature={this.state.temperature} 
      humidity={this.state.humidity}
      city={this.state.city}
      country={this.state.country}
      description={this.state.description}
      error={this.state.error}
              />

  </div>
 );
}

};

导出默认应用程序;`

1 个答案:

答案 0 :(得分:1)

您的组件没有任何默认状态,因此this.state将是null,并且尝试从中访问temperature属性将引起您的错误。

写入state = { ... }而不是state: { ... },您的组件将获得默认状态,并且可以正常工作。

class App extends React.Component {
  state = {
    temperature: undefined,
    city: undefined,
    country: undefined,
    humidity: undefined,
    description: undefined,
    error: undefined
  };

  // ...
}
相关问题