我是一个反应的新手-我得到了这个TypeError: Cannot read property 'temperature' of null,它不允许我将温度变量绑定到return()中的组件。在绑定之前,我可以在控制台中看到数据。代码:`类应用扩展React.Component {状态:{温度:未定义,城市:未定义,国家:未定义,湿度:未定义,描述:未定义,错误:未定义} getWeather = async (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>
);
}};
导出默认应用;`
发布于 2019-03-25 18:21:09
您的组件没有任何默认状态,因此this.state将为null,尝试从中访问temperature属性将导致错误。
编写state = { ... }而不是state: { ... },您的组件将被赋予默认状态,它将按预期工作。
class App extends React.Component {
state = {
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
error: undefined
};
// ...
}https://stackoverflow.com/questions/55335459
复制相似问题