Reactjs TypeError:无法读取属性';温度';空的
我是一个反应新手-我得到了这个Reactjs TypeError:无法读取属性';温度';空的,reactjs,api,data-binding,Reactjs,Api,Data Binding,我是一个反应新手-我得到了这个TypeError:cannotread属性'temperature'为null,它不允许我将温度变量绑定到return()中的组件。在绑定之前,我可以在控制台中查看数据。 代码: `类应用程序扩展了React.Component{ 声明:{ 温度:未定义, 城市:未定义, 国家:未定义, 湿度:未定义, 说明:未定义, 错误:未定义 } getWeather=async(e)=>{ e、 预防默认值() const city=e.target.elements.c
TypeError:cannotread属性'temperature'为null
,它不允许我将温度变量绑定到return()
中的组件。在绑定之前,我可以在控制台中查看数据。
代码:
`类应用程序扩展了React.Component{
声明:{
温度:未定义,
城市:未定义,
国家:未定义,
湿度:未定义,
说明:未定义,
错误:未定义
}
getWeather=async(e)=>{
e、 预防默认值()
const city=e.target.elements.city.value;
const country=e.target.elements.country.value;
常量api_调用=等待
取回(`http://api.openweathermap.org/data/2.5/weather?
q=${city}、${country}&appid=${API_KEY}&units=metric`);
const data=wait api_call.json();
控制台日志(数据);
这是我的国家({
温度:data.main.temp,
城市:data.name,
国家:data.sys.country,
湿度:data.main.湿度,
description:data.weather[0]。description,
错误:“
});
}
render(){
返回(
检查天气组件
);
}
})
导出默认应用程序` 您的组件没有任何默认状态,因此
此.state
将为null
,尝试从中访问温度属性将导致错误
写入state={…}
而不是state:{…}
时,组件将被赋予默认状态,并且它将按预期工作
class App extends React.Component {
state = {
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
error: undefined
};
// ...
}
class App extends React.Component {
state = {
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
error: undefined
};
// ...
}