首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError:无法读取null的属性“temperature”

TypeError:无法读取null的属性“temperature”
EN

Stack Overflow用户
提问于 2019-03-25 18:14:05
回答 1查看 543关注 0票数 1

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

代码语言:javascript
复制
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>
 );
}

};

导出默认应用;`

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-25 18:21:09

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

编写state = { ... }而不是state: { ... },您的组件将被赋予默认状态,它将按预期工作。

代码语言:javascript
复制
class App extends React.Component {
  state = {
    temperature: undefined,
    city: undefined,
    country: undefined,
    humidity: undefined,
    description: undefined,
    error: undefined
  };

  // ...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55335459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档