【问题标题】:TypeError: Cannot read property 'temperature' of nullTypeError:无法读取 null 的属性“温度”
【发布时间】:2019-03-25 10:14:05
【问题描述】:

我是 React 的新手 - 我得到了这个 TypeError: Cannot read property 'temperature' of null,它不允许我将温度变量绑定到 return() 中的组件。我可以在绑定之前在控制台中看到数据。 代码 : `class App 扩展 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>
 );
}

};

导出默认应用;`

【问题讨论】:

    标签: reactjs api data-binding


    【解决方案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
      };
    
      // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 1970-01-01
      • 2020-01-29
      • 2018-03-27
      • 2022-01-12
      • 2021-12-04
      • 2021-12-17
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多